How to remove array key in PHP?

Guanhui
Release: 2023-03-01 16:52:01
Original
3684 people have browsed it

How to remove array key in PHP?

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));
?>
Copy after login

The above routine will output:

Array
(
    [0] => XL
    [1] => gold
)
Copy after login


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
)
?>
Copy after login
<?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(
    &#39;foo&#39; => &#39;foo&#39;,
    &#39;bar&#39; => array(
        &#39;baz&#39; => &#39;baz&#39;,
        &#39;candy&#39; => &#39;candy&#39;,
        &#39;vegetable&#39; => array(
            &#39;carrot&#39; => &#39;carrot&#39;,
        )
    ),
    &#39;vegetable&#39; => array(
        &#39;carrot&#39; => &#39;carrot2&#39;,
    ),
    &#39;fruits&#39; => &#39;fruits&#39;,
);

var_dump(array_value_recursive(&#39;carrot&#39;, $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive(&#39;apple&#39;, $arr)); // null
var_dump(array_value_recursive(&#39;baz&#39;, $arr)); // string(3) "baz"
var_dump(array_value_recursive(&#39;candy&#39;, $arr)); // string(5) "candy"
var_dump(array_value_recursive(&#39;pear&#39;, $arr)); // null
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template