Home >Backend Development >PHP Tutorial >Detailed explanation of PHP 5.2.x array operation examples
ArrayOperations in php 5.2.x
I just watched the php introductory tutorial and summarized some php array operations caused by different php versions. question.
The following content was tested in the php5.2.5 environment.
1,
<?php $arr = array("a" => 1,"b" => 2,"c" => 3);
If you define an array like this, a compilation error will be reported:
Copy code code example:
<?php $arr = array("a" = 1,"b" = 2,"c" = 3);
Therefore, when defining an array, you can only use =>
Copy code example:
<?php $arr = array("a" => 1,"b" => 2,"c" => 3); echo $arr[0]; echo $arr[1];
What is typed is Blank.
Correct printing method:
Copy code Code example:
echo $arr["a"];
3. Add elements Or when modifying elements, you can only use =, not =>
Copy code Code example:
<?php $arr = array("a" => 1,"b" => 2,"c" => 3); $arr["c"] => 6;
The above operation method, A compilation error will occur in php 5.2.5
To add elements or modify elements, write like this:
Copy code code example:
<?php $arr = array("a" => 1,"b" => 2,"c" => 3); $arr["d"] = 4; $arr["c"] = 6;
To delete elements, use unset:
Copy code Code example:
unset ($arr["c"]);
4. Think about the following code, what will be output?
Copy code Code example:
<?php $arr = array("a" => 1,2,"b" => 3,4); $arr[] = 5; foreach($arr as $key => $value) { echo "key:$key value:$value<br>"; }
Output result:
key:a value:1 key:0 value:2 key:b value:3 key:1 value:4 key:2 value:5
Description: Only if When the user does not define a key, PHP will automatically use a number starting from 0 as the key.
5. Arrays in php have pointers, and you can perform forward and backward operations on the array
Copy code code example:
<?php $arr = array("a" => 1,3,"b" => 2);
//Create After completing the array, the default pointer points to the first element
echo current($arr)."0c6dc11e160d3b678d68754cc175188a";
//Advance one position
echo next($arr )."0c6dc11e160d3b678d68754cc175188a";
//The default principle of sorting is from small to large
sort($arr);
//After sorting, the array pointer stops at the first element
echo current($arr)."0c6dc11e160d3b678d68754cc175188a";
echo next($arr)."0c6dc11e160d3b678d68754cc175188a";
//Go back one position
echo prev($arr). "0c6dc11e160d3b678d68754cc175188a";
Output result:
13121
The above is the detailed content of Detailed explanation of PHP 5.2.x array operation examples. For more information, please follow other related articles on the PHP Chinese website!