Home>Article>Backend Development> PHP array keys can use numbers or something

PHP array keys can use numbers or something

WBOY
WBOY Original
2022-09-20 17:29:10 2302browse

PHP array keys can use numbers or strings, and it also supports using a mixture of strings and numbers as key names for associative arrays; element values in PHP arrays can be of any type, but key names can only be numbers or Composed of strings, each number corresponds to the position of an array element in the array.

PHP array keys can use numbers or something

The operating environment of this article: Windows 10 system, PHP version 8.1, Dell G3 computer

php array keys can use numbers or something

The value in the array can be of any type, but the key name can only be numbers and strings

In PHP, the array array is a set of ordered variables. Each value is called an element. Each element is distinguished by a special identifier called a key (also called a subscript).

PHP arrays are more flexible than arrays in other high-level languages. They not only support index arrays with numbers as keys, but also support associative arrays with strings or a mixture of strings and numbers as keys.

The subscript (key name) of the index array consists of numbers, starting from 0 by default. Each number corresponds to the position of an array element in the array. There is no need to specify it. PHP will automatically set the key of the index array. Assign an integer value to the name, and then automatically increment from this value.

Extension: PHP changes the array key name to a number

You can use the array_values() function to change the array key name to a number. The function can get the values of all elements in the array and convert the associative array into an index array, then the key name of the array becomes a number; the syntax is "array_values(array)".

The example is as follows:

 '红色', "颜色2" => '黄色', "颜色3" => '蓝色', "颜色4" => '紫色'); echo '
'; var_dump(array_values($array)); ?>

Output result:

array (size=4) 0 => string '红色' (length=6) 1 => string '黄色' (length=6) 2 => string '蓝色' (length=6) 3 => string '紫色' (length=6)

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of PHP array keys can use numbers or something. 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