欢迎访问宙启技术站
智能推送

10个高效实用的PHP函数大全

发布时间:2023-06-26 17:56:52

1. str_replace

str_replace(string $find, string $replace, string $subject): string

替换字符串中的子串,$find表示要替换的子串,$replace表示用什么来替换子串,$subject表示要替换的字符串。

示例:

$str = "Hello world";

$new_str = str_replace("world", "PHP", $str);

echo $new_str; //输出Hello PHP

2. array_push

array_push(array &$array, mixed $value): int

向数组末尾添加一个或多个元素,$array表示要添加元素的数组,$value表示要添加到数组的元素。

示例:

$arr = array(1, 2);

array_push($arr, 3, 4);

print_r($arr); //输出Array([0]=>1 [1]=>2 [2]=>3 [3]=>4)

3. array_pop

array_pop(array &$array): mixed

从数组末尾删除并返回一个元素,$array表示要操作的数组。

示例:

$arr = array(1, 2, 3);

$pop_val = array_pop($arr);

print_r($arr); //输出Array([0]=>1 [1]=>2)

echo $pop_val; //输出3

4. implode

implode(string $separator, array $pieces): string

连接数组中的元素为一个字符串,$separator表示连接元素之间的分隔符,$pieces表示要连接的数组。

示例:

$arr = array("Hello", "world", "!");

$str = implode(" ", $arr);

echo $str; //输出Hello world !

5. explode

explode(string $delimiter, string $string, int $limit = PHP_INT_MAX): array

将字符串分割成数组,$delimiter表示分隔符,$string表示要分割的字符串,$limit表示分割成的数组元素数量限制。

示例:

$str = "Hello world !";

$arr = explode(" ", $str);

print_r($arr); //输出Array([0]=>Hello [1]=>world [2]=>!)

6. count

count(mixed $var, int $mode = COUNT_NORMAL): int

统计数组元素的个数或对象属性的个数,$var表示要统计的变量,$mode表示统计模式。

示例:

$arr = array(1, 2, 3);

echo count($arr); //输出3

$obj = new stdClass();

$obj->property1 = "Hello";

$obj->property2 = "world";

echo count($obj); //输出2

7. isset

isset(mixed ...$var): bool

检查变量是否已设置并且非NULL,可同时检查多个变量,返回true或false。

示例:

$str = "Hello world";

if(isset($str)){

    echo "str is set";

}

if(isset($str, $arr)){

    echo "str and arr are both set";

} else {

    echo "at least one of str and arr is not set";

}

8. empty

empty(mixed $var): bool

判断变量是否为空,包括值为NULL、""、0、"0"、false、array()等情况。返回true或false。

示例:

$str = "";

if(empty($str)){

    echo "str is empty";

}

9. header

header(string $string, bool $replace = true, int $http_response_code = null): void

发送HTTP头部信息,$string表示要发送的HTTP头部信息,如Content-Type、Location等,$replace表示是否替换已经发送的HTTP头部信息,$http_response_code表示HTTP响应码。

示例:

header("Content-Type: text/plain");

echo "Hello world";

10. file_get_contents

file_get_contents(string $filename, bool $use_include_path = false, resource $context = null, int $offset = 0, int $maxlen = PHP_INT_MAX): string

读取整个文件到字符串中,$filename表示文件名或URL,$use_include_path表示是否在包含文件路径中搜索文件,$context表示流上下文,$offset表示从文件开始读取的偏移量,$maxlen表示最大读取的字节数。

示例:

$str = file_get_contents("http://www.example.com");

echo $str; //输出网页内容