Home  >  Article  >  Backend Development  >  The difference between php associative array and index array

The difference between php associative array and index array

藏色散人
藏色散人Original
2019-10-09 10:19:225538browse

The difference between php associative array and index array

The difference between php associative array and index array

Index array

Arrays with numbers as key names are generally called index arrays. An array whose keys are represented by strings is an associative array that will be introduced below. The keys of the index array are integers and start from 0 and so on.

Index array initialization example:

<pre name="code" class="php"><?php  
//创建一个索引数组,索引数组的键是“0”,值是“苹果”  
$fruit=array("苹果","香蕉");  
print_r($fruit);  
?>

Running result:

Array
(
    [0] => 苹果
    [1] => 香蕉
)

Three assignment methods for index array:

1.array[0]=&#39;苹果&#39;;
2.$arr=array(&#39;0&#39;=>&#39;苹果&#39;);
3.$arr=array(&#39;苹果&#39;);

Example:

<?php  
//请创建一个数组变量arr,并尝试创建一个索引数组,键是0,值是苹果  
$arr=array(0=>&#39;苹果&#39;);  
if( isset($arr) ) {print_r($arr);}  
?>

You can use for and foreach to access the elements in the array, because for is easier. Here are just examples of using foreach,

<?php  
$fruit=array(&#39;苹果&#39;,&#39;香蕉&#39;,&#39;菠萝&#39;);  
foreach($fruit as $key=>$value){  
    echo &#39;<br>第&#39;.$key.&#39;值是:&#39;.$value;  
}  
  
?>

Running results:

第0值是:苹果
第1值是:香蕉
第2值是:菠萝

Note: Here $key is the key The value $value is the element value

Associative array

In fact, the difference between associative array and index array is only in the key value. The key value of associative array is a string. And it is an artificial regulation, for example:

<?php  
//创建一个关联数组,关联数组的键“orange”,值是“橘子”  
$fruit=array(&#39;orange&#39;=>&#39;橘子&#39;);  
echo $fruit[&#39;orange&#39;];  
?>

The remaining initialization, assignment, and foreach usage are basically the same.

For more PHP knowledge, please visit PHP Chinese website!

The above is the detailed content of The difference between php associative array and index array. 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
Previous article:What does php mainly do?Next article:What does php mainly do?