在PHP中,我们可以使用数组来存储和操作数据库查询的结果,以下是一些常见的PHP数组函数和它们的用法:
1、array_push()
:向数组末尾添加一个或多个元素。
$arr = array("apple", "banana"); array_push($arr, "orange", "grape"); print_r($arr);
输出结果:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
2、array_pop()
:删除并返回数组最后一个元素。
$arr = array("apple", "banana", "orange", "grape"); $last = array_pop($arr); print_r($arr); echo $last;
输出结果:
Array ( [0] => apple [1] => banana [2] => orange ) grape
3、array_shift()
:删除并返回数组第一个元素。
$arr = array("apple", "banana", "orange", "grape"); $first = array_shift($arr); print_r($arr); echo $first;
输出结果:
Array ( [0] => banana [1] => orange [2] => grape ) apple
4、array_unshift()
:在数组开头添加一个或多个元素。
$arr = array("banana", "orange", "grape"); array_unshift($arr, "apple", "pear"); print_r($arr);
输出结果:
Array ( [0] => apple [1] => pear [2] => banana [3] => orange [4] => grape )
5、in_array()
:检查数组中是否存在指定的值。
$arr = array("apple", "banana", "orange", "grape"); if (in_array("banana", $arr)) { echo "banana is in the array"; } else { echo "banana is not in the array"; }
输出结果:
banana is in the array
6、array_search()
:在数组中查找指定的值,如果找到则返回对应的键名。
$arr = array("apple", "banana", "orange", "grape"); $key = array_search("orange", $arr); echo "The key of 'orange' is: " . $key;
输出结果:
The key of 'orange' is: 2
7、array_keys()
:返回数组中所有的键名。
$arr = array("apple" => 1, "banana" => 2, "orange" => 3, "grape" => 4); $keys = array_keys($arr); print_r($keys);
输出结果:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
8、array_values()
:返回数组中所有的值。
$arr = array("apple" => 1, "banana" => 2, "orange" => 3, "grape" => 4); $values = array_values($arr); print_r($values);
输出结果:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
9、array_merge()
:合并两个或多个数组。
$arr1 = array("apple", "banana"); $arr2 = array("orange", "grape"); $merged = array_merge($arr1, $arr2); print_r($merged);
输出结果:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
10、array_slice()
:从数组中提取指定范围的元素。
$arr = array("apple", "banana", "orange", "grape"); $sliced = array_slice($arr, 1, 2); print_r($sliced);
输出结果:
Array ( [0] => banana [1] => orange )
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/674597.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复