In PHP, array is a very common data type. When using arrays, we need to choose which array type to use based on specific needs. There are two main types of arrays in PHP: indexed arrays and associative arrays.
1. Index array
Index array means that each element in the array has a unique numerical index value. This index value is incremented starting from 0, and each index value corresponds to an element in the array. For example:
$array = array("apple", "banana", "pear");
The above code defines an index array, which contains 3 elements. The indices of these three elements are 0, 1, and 2 respectively. We can use the following code to access elements in the array:
echo $array[0]; // 输出“apple” echo $array[1]; // 输出“banana” echo $array[2]; // 输出“pear”
The characteristic of indexed arrays is that each element has a unique numeric index value, and these index values increment from 0. This array type is very commonly used in many situations, such as looping through arrays, sorting by index value, etc.
2. Associative array
Associative array means that each element in the array has a unique string index value. These string index values are called keys, and each key corresponds to an element in the array. For example:
$person = array("name"=>"张三", "age"=>20, "gender"=>"男");
The above code defines an associative array, which contains 3 elements. Each element contains a key and a value. Keys and values are associated using the "=>" symbol. We can use the following code to access elements in the array:
echo $person["name"]; // 输出“张三” echo $person["age"]; // 输出“20” echo $person["gender"]; // 输出“男”
The characteristic of associative arrays is that each element has a unique string index value, and these index values are arbitrary. This array type is very commonly used in many situations, such as representing configuration files, database query results, etc.
Summary:
In PHP, array is a very important data type. Depending on different needs, we can choose to use index arrays or associative arrays. Indexed arrays are suitable for sequential access, and associative arrays are suitable for fast lookups. In actual development, we need to choose which array type to use based on specific scenarios.
The above is the detailed content of What are the two types of arrays in php?. For more information, please follow other related articles on the PHP Chinese website!