$v){$arr2[]=$k;}"."/> $v){$arr2[]=$k;}".">
Home > Article > Backend Development > How to make an array retain only key names in php
Two implementation methods: 1. Use the array_keys() function to obtain all key names of the array, with the syntax "array_keys (array)"; if you want to retain the key names of the specified value, you can set the second and third Parameters, syntax "array_keys (array, specified value, type is consistent)". 2. Use a foreach loop and an empty array to obtain all the key names of the array. The syntax is "foreach($arr1 as $k=>$v){$arr2[]=$k;}".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php Two ways to make the array only retain key names
Method 1: Use the array_keys() function to get all the key names of the array
array_keys() The function can retrieve some or all keys in the array.
array_keys(array,value,strict)
Parameters | Description |
---|---|
array | Required . Specifies an array. |
value | Optional. You can specify a key value, and then only the key name corresponding to that key value will be returned. |
strict | Optional. Used with the value parameter. Possible values:
|
When you want to get all key names, just set the first parameter and omit the second and third parameters.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr=array("Name"=>"Peter","Age"=>"41","Country"=>"USA"); var_dump($arr); $keys=array_keys($arr); echo "数组只保留键名:"; var_dump($keys); ?>
If you want to get the key name of the specified value, the second and third parameters are not omitted
<?php header("Content-type:text/html;charset=utf-8"); $arr=array("Name"=>"Peter","Age1"=>"41","Age2"=>41,"Country"=>"USA"); var_dump($arr); $keys1=array_keys($arr,41); echo "数组只保留键名:"; var_dump($keys1); $keys2=array_keys($arr,41,true); var_dump($keys2); ?>
Method 2: Use a foreach loop and an empty array to get all the key names of the array
Implementation idea:
Use a foreach loop to traverse the key names and key values of the original array, and only assign the key names to the empty array.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr1=array("aaa"=>11,"bbb"=>22,"ccc"=>33); var_dump($arr1); $arr2=array(); foreach($arr1 as $k=>$v){ $arr2[]=$k; } echo "数组只保留键名:"; var_dump($arr2); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to make an array retain only key names in php. For more information, please follow other related articles on the PHP Chinese website!