|
Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index
PHP Script Tips - Understanding PHP Arrays and Their Basic Operations
By: FYICenter.com
Part:
1
2
3
4
(Continued from previous part...)
Can You Copy an Array?
You can create a new array by copying an existing array using the assignment statement.
Note that the new array is not a reference to the old array.
If you want a reference variable pointing to the old array,
you can use the reference operator "&".
Here is a PHP script on how to copy an array:
<?php
$oldArray = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$newArray = $oldArray;
$refArray = &$oldArray;
$newArray["One"] = "Python";
$refArray["Two"] = "C#";
print("\$newArray[\"One\"] = ".$newArray["One"]."\n");
print("\$oldArray[\"One\"] = ".$oldArray["One"]."\n");
print("\$refArray[\"Two\"] = ".$refArray["Two"]."\n");
print("\$oldArray[\"Two\"] = ".$oldArray["Two"]."\n");
?>
This script will print:
$newArray["One"] = Python
$oldArray["One"] = Perl
$refArray["Two"] = C#
$oldArray["Two"] = C#
How to Loop through an Array?
The best way to loop through an array is to use the "foreach" statement.
There are two forms of "foreach" statements:
- foreach ($array as $value) {} - This gives you only one temporary variable to hold the current value in the array.
- foreach ($array as $key=>$value) {} - This gives you two temporary variables to hold the current key and value in the array.
Here is a PHP script on how to use "foreach" on an array:
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$array["3"] = "C+";
$array[""] = "Basic";
$array[] = "Pascal";
$array[] = "FORTRAN";
print("Loop on value only:\n");
foreach ($array as $value) {
print("$value, ");
}
print("\n\n");
print("Loop on key and value:\n");
foreach ($array as $key=>$value) {
print("[$key] => $value\n");
}
?>
This script will print:
Loop on value only:
PHP, Perl, Java, C+, Basic, Pascal, FORTRAN,
Loop on key and value:
[Zero] => PHP
[One] => Perl
[Two] => Java
[3] => C+
[] => Basic
[4] => Pascal
[5] => FORTRAN
How the Values Are Ordered in an Array?
PHP says that an array is an ordered map. But how the values are ordered in an array?
The answer is simple. Values are stored in the same order as they are inserted like a queue.
If you want to reorder them differently, you need to use a sort function.
Here is a PHP script show you the order of array values:
<?php
$mixed = array();
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$mixed["Two"] = "";
unset($mixed[4]);
print("Order of array values:\n");
print_r($mixed);
?>
This script will print:
Order of array values:
Array
(
[Two] =>
[3] => C+
[Zero] => PHP
[1] => Perl
[] => Basic
[5] => FORTRAN
)
(Continued on next part...)
Part:
1
2
3
4
|