How to remove array key in PHP?
In PHP, you can use the "array_values()" function to remove the array key. The function of this function is to get all the values in the array. Its usage is "array_values($array)", and its parameter " $array" represents the array from which the key is to be removed, and the return value is an index array containing all values.
Recommended video tutorial: "PHP programming from entry to master (learning route)"
Simple example
<?php $array = array("size" => "XL", "color" => "gold"); print_r(array_values($array)); ?>
The above routine will output:
Array ( [0] => XL [1] => gold )
Usage example
<?php $a = array( 3 => 11, 1 => 22, 2 => 33, ); $a[0] = 44; print_r( array_values( $a )); ==> Array( [0] => 11 [1] => 22 [2] => 33 [3] => 44 ) ?>
<?php /** * Get all values from specific key in a multidimensional array * * @param $key string * @param $arr array * @return null|string|array */ function array_value_recursive($key, array $arr){ $val = array(); array_walk_recursive($arr, function($v, $k) use($key, &$val){ if($k == $key) array_push($val, $v); }); return count($val) > 1 ? $val : array_pop($val); } $arr = array( 'foo' => 'foo', 'bar' => array( 'baz' => 'baz', 'candy' => 'candy', 'vegetable' => array( 'carrot' => 'carrot', ) ), 'vegetable' => array( 'carrot' => 'carrot2', ), 'fruits' => 'fruits', ); var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" } var_dump(array_value_recursive('apple', $arr)); // null var_dump(array_value_recursive('baz', $arr)); // string(3) "baz" var_dump(array_value_recursive('candy', $arr)); // string(5) "candy" var_dump(array_value_recursive('pear', $arr)); // null ?>
Recommended tutorial : "PHP Tutorial"
The above is the detailed content of How to remove array key in PHP?. For more information, please follow other related articles on the PHP Chinese website!