Home  >  Article  >  Backend Development  >  How to use keys in php arrays

How to use keys in php arrays

伊谢尔伦
伊谢尔伦Original
2017-06-22 17:49:202720browse

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 &#39;One&#39; defined? ".array_key_exists("One", $array)."\n");
print("Is &#39;1&#39; defined? ".array_key_exists("1", $array)."\n");
print("Is &#39;Two&#39; defined? ".isset($array["Two"])."\n");
print("Is &#39;2&#39; defined? ".isset($array[2])."\n");
?>

The return result is as follows:

Is &#39;One&#39; defined? 1
Is &#39;1′ defined?
Is &#39;Two&#39; defined? 1
Is &#39;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(&#39;vegetable&#39;, $items);
 
echo $key;//tomato
 
//2.返回多个键名
$keys=array_keys($items,&#39;vegetable&#39;);
 
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!

Statement:
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