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

PHP函数库大全-常用函数及代码示例

发布时间:2023-06-25 06:50:47

PHP是一种功能强大的编程语言,具有丰富的函数库和代码示例。以下是常用的PHP函数库及代码示例:

1. 字符串函数

a. strlen($str):返回字符串的长度

$str = "Hello World!";

echo strlen($str);

输出结果:12

b. strpos($str, $find):返回子字符串在字符串中 次出现的位置

$str = "Hello World!";

echo strpos($str, "World");

输出结果:6

c. str_replace($old, $new, $str):替换字符串中的指定文本

$str = "Hello World!";

echo str_replace("World", "PHP", $str);

输出结果:Hello PHP!

2. 数组函数

a. array_count_values($arr):返回数组中每个值出现的次数

$arr = array("a", "b", "c", "a", "d");

print_r(array_count_values($arr));

输出结果:Array ( [a] => 2 [b] => 1 [c] => 1 [d] => 1 )

b. array_push($arr, $val):往数组尾部添加一个或多个元素

$arr = array("a", "b", "c");

array_push($arr, "d", "e");

print_r($arr);

输出结果:Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )

c. array_slice($arr, $offset, $length):返回数组的一个片段

$arr = array("a", "b", "c", "d", "e");

print_r(array_slice($arr, 2, 3));

输出结果:Array ( [0] => c [1] => d [2] => e )

3. 数据库函数

a. mysqli_connect($host, $user, $pass, $name):连接到MySQL数据库

$con = mysqli_connect("localhost", "root", "", "my_db");

if(mysqli_connect_errno()){

    echo "Failed to connect to MySQL: " . mysqli_connect_error();

    exit;

}

b. mysqli_query($con, $sql):向数据库发出SQL查询语句并返回结果

$sql = "SELECT * FROM users WHERE age > 18";

$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)) {

    echo $row['name'] . "

";

}

c. mysqli_close($con):关闭与数据库的连接

mysqli_close($con);

4. 文件操作函数

a. fopen($filename, $mode):打开文件并返回文件句柄

$handle = fopen("test.txt", "r");

b. fwrite($handle, $content):向打开的文件中写入内容

$handle = fopen("test.txt", "w");

fwrite($handle, "Hello World!");

c. fclose($handle):关闭文件并释放文件句柄

fclose($handle);

以上是常用的PHP函数库及代码示例,有助于初学者了解和使用PHP函数。