In PHP, the key value of an array element is a unique identifier associated with each element. This key value can be a number, a string, or a null value, but it must be unique in the array.
In PHP, there are two types of arrays: indexed arrays and associative arrays. For indexed arrays, the key values are numbers, starting from 0 and increasing. For associative arrays, the key values can be any string or number.
In an indexed array, you can access the array elements using the following methods:
$myArray = array("apple", "banana", "cherry"); echo $myArray[0]; // 输出 "apple" echo $myArray[1]; // 输出 "banana" echo $myArray[2]; // 输出 "cherry"
In an associative array, you can access the array elements using the following methods:
$myArray = array("fruit1" => "apple", "fruit2" => "banana", "fruit3" => "cherry"); echo $myArray["fruit1"]; // 输出 "apple" echo $myArray["fruit2"]; // 输出 "banana" echo $myArray["fruit3"]; // 输出 "cherry"
In an association In an array, key values can also be numbers. For example:
$myArray = array(10 => "apple", 20 => "banana", 30 => "cherry"); echo $myArray[10]; // 输出 "apple" echo $myArray[20]; // 输出 "banana" echo $myArray[30]; // 输出 "cherry"
It is worth noting that if an undefined key is used to access an array element, a PHP warning will be returned and the value will be set to null by default. For example:
$myArray = array("apple", "banana", "cherry"); echo $myArray[3]; // 输出PHP警告,返回null
Similarly, in an associative array, if an undefined key is used to access an array element, null will also be returned. For example:
$myArray = array("fruit1" => "apple", "fruit2" => "banana", "fruit3" => "cherry"); echo $myArray["fruit4"]; // 输出null
In short, the key value of a PHP array element can be a number or a string, and must be unique. For an indexed array, the key value is an increasing number starting from 0; for an associative array, the key value can be any string or number. When accessing an array element using an undefined key, a PHP warning or null value will be returned.
The above is the detailed content of What are the key values of array elements in PHP. For more information, please follow other related articles on the PHP Chinese website!