PHP数组常用函数

// count():取数组长度
$myArray = [1, 2, 3, 4, 5];
$count = count($myArray); // 返回 5

// array_push():将元素添加到数组末尾
$fruits = ['apple', 'banana'];
array_push($fruits, 'orange', 'mango');
//结果: $fruits = ['apple', 'banana', 'orange', 'mango']

// array_pop():删除数组末尾元素,并返回它
$fruits = ['apple', 'banana', 'orange'];
$removedFruit = array_pop($fruits);
//结果: $removedFruit = 'orange', $fruits = ['apple', 'banana']

// array_shift():删除数组头部元素,并返回它
$fruits = ['apple', 'banana', 'orange'];
$removedFruit = array_shift($fruits);
//结果: $removedFruit = 'apple', $fruits = ['banana', 'orange']

// array_merge():数组合并
$array1 = ['apple', 'banana'];
$array2 = ['orange', 'mango'];
$mergedArray = array_merge($array1, $array2);
//结果: $mergedArray = ['apple', 'banana', 'orange', 'mango']

// is_array($var):判断是否为数组
$array = [1, 2, 3];
$result = is_array($array); // 返回 true
$notArray = 'hello';
$result = is_array($notArray); // 返回 false

// explode($delimiter, $string):拆分字符串为数组。
$string = "apple,banana,orange";
$array = explode(",", $string);
// $array = ['apple', 'banana', 'orange']

// implode($glue, $array):将数组转为字符串
$array = ['apple', 'banana', 'orange'];
$string = implode(",", $array);
// $string = "apple,banana,orange"

// unset($array[key]):删除数组中指定键的元素。
$fruits = ['apple', 'banana', 'orange'];
unset($fruits[1]); // 删除索引为1的元素
// $fruits = ['apple', 'orange']
$person = ['name' => 'John', 'age' => 25];
unset($person['age']); // 删除键为'age'的元素
// $person = ['name' => 'John']

// sort($array):对数组升序排列。
$numbers = [3, 1, 2, 4];
sort($numbers);
// $numbers = [1, 2, 3, 4]

rsort($array):对数组降序排列
$numbers = [3, 1, 2, 4];
rsort($numbers);
// $numbers = [4, 3, 2, 1]

// ksort($array):按键对数组升序
$fruits = ['Banana' => 2, 'Apple' => 3, 'Orange' => 1];
ksort($fruits);
// $fruits = ['Apple' => 3, 'Banana' => 2, 'Orange' => 1]

// krsort($array):按键对数组降序
$fruits = ['Banana' => 2, 'Apple' => 3, 'Orange' => 1];
krsort($fruits);
// $fruits = ['Orange' => 1, 'Banana' => 2, 'Apple' => 3]

 

posted @ 2023-06-18 01:37  波罗斯の程序日记  阅读(3)  评论(0编辑  收藏  举报