1. Determine whether the specified key exists in the array
There are two functions in php to determine whether the array contains the specified key, namely array_key_exists and isset
array_key_exists syntax is as follows
array_key_exists($key, $array)
If the key exists, it returns true. The isset function syntax is as follows
isset($array[$key])
If the key exists, it returns true
The demo code is as follows:
<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java"); print("Is 'One' defined? ".array_key_exists("One", $array)."\n"); print("Is '1' defined? ".array_key_exists("1", $array)."\n"); print("Is 'Two' defined? ".isset($array["Two"])."\n"); print("Is '2' defined? ".isset($array[2])."\n"); ?>
The return result is as follows:
Is 'One' defined? 1 Is '1′ defined? Is 'Two' defined? 1 Is '2′ defined?
2. Some tips for using array key names
$arr[true] is equivalent to $arr[1]; $arr[false] is equivalent to $ arr[0].
Using null as the key name is equivalent to creating or overwriting an $arr[null], which can be accessed using $arr[null] or $arr[""].
When using a number with a decimal point as the key name, the key name will automatically intercept the integer part as the key name. For example, $arr[123.45]=5, you can use $arr[123.45] or $arr[123] to obtain the key value; when traversing with foreach, $arr[123] is used.
$arr[]=5, the element will be added after the array $arr.
Note: The data type of the key name in the array is integer or string type
3. The array obtains the key name based on the value
php arrayGet the key name function based on the value. There are two main built-in functions that can be used. array_search and array_keys are used to handle returning single key names and multiple key names.
Specific examples are as follows:
<?php /** * php array get key by value * php数组根据值获取键名 */ $items = array( "banana" => "fruit", "tomato" => "vegetable", "lentil" => "bean", "apple" => "vegetable" ); //1.返回一个键名,如果值有重复返回第一个键名 $key = array_search('vegetable', $items); echo $key;//tomato //2.返回多个键名 $keys=array_keys($items,'vegetable'); print_r($keys); /* Array ( [0] => tomato [1] => apple ) */ ?>
The above is the detailed content of How to use keys in php arrays. For more information, please follow other related articles on the PHP Chinese website!