How to remove key values ​​from an array in PHP?

Guanhui
Release: 2023-03-01 14:30:02
Original
4192 people have browsed it

How to remove key values ​​from an array in PHP?

#PHP How to remove key values ​​from an array?

In PHP, you can use the "array_values()" function to remove key values ​​from the array. This function will return all the values ​​in the array. Its syntax is "array_values(array)", and its parameter array represents The array to be operated on, the return value is an indexed array containing all values.

Sample code

<?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
<?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

The above is the detailed content of How to remove key values ​​from an array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!