PHP - Using Arrays
From Global Programming Syntax
Arrays are an important part of php as they allow you to loop through a specific group of data and collect data from loops. In the below chapters you will learn how to make, modify and delete arrays.
Contents |
Creating an array using the array function
There are several ways of creating an array and the easiest will depend on how you plan to populate the array. If for example you wanted to create an array with some specific data then the following is how you would create it.
$array_var=array('apple','orange','banana','salt');
Now that is a basic array containing four values. But one might question, "how do I view the data for testing purposes". Well there is a function for that called print_r(). If the print_r() function is used on the above function below is the code and the results.
<?php
$array_var=array('apple','orange','banana','salt');
echo '<xmp>';
print_r($array_var);
echo '</xmp>';
?>
=============================
Above will display the below:
=============================
Array
(
[0] => apple
[1] => orange
[2] => banana
[3] => salt
)
You may have noticed that surrounding the print_r function is two echo functions displaying an <xmp></xmp> tag. This is so that the text will display in mono-print and won't be jumbled on the one line.
To read what that output means, the first two lines and the last line says that the item $array_var is an array. Then below that it show the key in brackets then an arrow pointing to the value. The keys are basically what are between the brackets when you call an array such as $array_var[0] or $array_var[1]. So an example of the usage is the following
echo $array_var[0]; //outputs: apple
echo $array_var[1]; //outputs: orange
echo $array_var[3]; //outputs: salt
Next is say you wanted the numbers in that array to be letters. Well it is possible to use anything you like as a key. Consider the following example:
<?php
$array_var=array('a'=>'apple','b'=>'orange','c'=>'banana','d'=>'salt');
echo '<xmp>';
print_r($array_var);
echo '</xmp>';
?>
=============================
Above will display the below:
=============================
Array
(
[a] => apple
[b] => orange
[c] => banana
[d] => salt
)
Again same thing but this time the keys are specified. So basically you define the keys in a similar way they are displayed with print_r().
Using loops to populate arrays
Loops are one of the most common methods used to populate arrays as it allows for a variable number values to be stored in an array with each variable containing its unique value. In comparison to using the array() function, the array() function has a fixed number of values meaning you have to specify how many values although the array() function can be faster. If you were cleaver enough to understand that description then your a genius and should have no problem with the following otherwise just stick to the simplified descriptions below.
USING AN ARRAY WITH A WHILE LOOP
Since many noobs have troubles with for() loops it is probably best to start with a simple while loop. Let's first place make a sentence and put every unique character of that sentence into an array so that you every character of the sentence in an array with no repeated characters. So lets consider the following example:
<?php
$sentence='Hello world! This will be split into an array.';
//configure the above.
$letter=str_split($sentence,1);
$result=array();
$array_key=0;
while (isset($letter[$array_key])) {
if (!isset($tmp[$letter[$array_key]])) {
$tmp[$letter[$array_key]]=true;
$result[]=$letter[$array_key];
}
$array_key+=1;
}
unset($tmp,$letter);
//now to dump the array
echo '<xmp>';
print_r($result);
//now to display the new string
echo "------------------------\n";
echo implode('',$result);
echo '</xmp>';
?>
The above will display the below:
Array
(
[0] => H
[1] => e
[2] => l
[3] => o
[4] =>
[5] => w
[6] => r
[7] => d
[8] => !
[9] => T
[10] => h
[11] => i
[12] => s
[13] => b
[14] => p
[15] => t
[16] => n
[17] => a
[18] => y
[19] => .
)
------------------------
Helo wrd!Thisbptnay.
As complicated as this code looks you don't get much simpler with such great efficiency. To program for a computer you need to think like a computer. So below is an explanation of each part of the script.
Part 1
<?php
$sentence='Hello world! This will be split into an array.';
//configure the above.
$letter=str_split($sentence,1);
$result=array();
$array_key=0;
The first line of the above snippet is the standard php opening as you should know. On the second line is the string/sentence that will be used to find the unique letters from. Below that is a comment saying you can change the variable $sentence. Then below the comment in the above snippet is where the action begins. The function str_split is used to split the string after every 1 character(s) and assign this new array into $letter. After that is the end result array being defined then just before the while loop the array key variable is set to 0.
Part 2
while (isset($letter[$array_key])) {
This is a little trick you can use to loop through an array and it will continue to loop until it reaches the end of the array. So basically in the loop statement is the isset() function that checks that the array with its key is set.
Part 3
if (!isset($tmp[$letter[$array_key]])) {
$tmp[$letter[$array_key]]=true;
$result[]=$letter[$array_key];
}
The if statement here works just like the loop statement except it checks if an array key is not set. So if $tmp[/*letter*/] hasn't been set then it will pass the if statement. Then on the following line it defines that array value so the same if statement with the same letter will not pass a second time. If your wondering why the value true was given that is because it is the smallest value you can provide a variable along with false. True and false are called booleans as they contain 1 byte of data saying yes or no with true being yes. The same way digital data works (with ones and zeros). Then below the second line of the above code snippet is the letter being added to the $result array. You may notice how there are the two brackets before the = symbol. That is how you auto append to an array making the computer decide the array key. Then on the last line is the closing of the if statement.
Part 4
$array_key+=1;
}
unset($tmp,$letter);
The first line of the above snippet is the number one being added to the current value of the array key. This line is very important because if you don't have the first line of the above snippet then you will have an infinite loop that will crash the server. Just a thing to keep in mind and that is why it is best to always test your loops with WAMP, XAMPP or LAMP. That way you will only crash your own computer if you make a good infinite loop. Then of course below the first line of the above code snippet is the closing bracket for the while loop. Then below that is the unset function to delete the variables $tmp and $letter.
Part 5
//now to dump the array
echo '<xmp>';
print_r($result);
//now to display the new string
echo "------------------------\n";
echo implode('',$result);
echo '</xmp>';
?>
The above code snippet basically dumps the array $result then displays what the array $result would be if you tied all the values together. But as usual, on the second line is the tag <xmp> being displayed. This tag basically telling the browser to display characters as their literal characters (not to display as html formatted) and to use their real spacing and line spacing. Then the print_r() function is used to dump the array $result. Then there is a gap separating the previous part of code with the new. A bunch of dashes are also displayed to separate the text then a new line character. Below that is the implode function.
The implode function basically tells php to loop through the array and as it goes through each loop it appends to a string the value of the current loop round then at the end of the loop returns to the function the string it attached the values to during the loop. So all of this is combined into one simple function. Additionally you can tell it to separate the values with one or more symbols/characters but in this example that is just an empty string.
On the second last line of the above snippet is the closing of the xmp tag and as you should know the last line is the closing of the php tag.
CONVERTING THE WHILE LOOP TO A FOR LOOP
It has been tested and proven that when dealing with numbers in the for loop statement, it is slightly faster to use a for loop instead of a while loop. Below is the conversion for you to compare.
<?php
$sentence='Hello world! This will be split into an array.';
//configure the above.
$letter=str_split($sentence,1);
$result=array();
$array_key=0;
while (isset($letter[$array_key])) {
if (!isset($tmp[$letter[$array_key]])) {
$tmp[$letter[$array_key]]=true;
$result[]=$letter[$array_key];
}
$array_key+=1;
}
unset($tmp,$letter);
//now to dump the array
echo '<xmp>';
print_r($result);
//now to display the new string
echo "------------------------\n";
echo implode('',$result);
echo '</xmp>';
?>
Above is the while loop and below is the for loop.
<?php
$sentence='Hello world! This will be split into an array.';
//configure the above.
$letter=str_split($sentence,1);
$result=array();
for ($array_key=0;isset($letter[$array_key]);$array_key++) {
if (!isset($tmp[$letter[$array_key]])) {
$tmp[$letter[$array_key]]=true;
$result[]=$letter[$array_key];
}
}
unset($tmp,$letter);
//now to dump the array
echo '<xmp>';
print_r($result);
//now to display the new string
echo "------------------------\n";
echo implode('',$result);
echo '</xmp>';
?>
Array Functions
When using arrays, you are bound to have the need to use one or more types of functions in the array library. So in the below categories are some of the different functions with their basic usage.
Sorting an array by its value
There are two functions which will allow you to sort an array by its value. One will allow you to sort in alphabetical order (asort) and the other in reverse-alphabetical order (arsort). These two functions both sort the array by its value and not its key. So below is an example of a demonstration.
<?php
$myarray=array('b'=>'apple',0=>'orange','a'=>'banana',2=>'salt',1=>'sauce');
//sort in reverse alphabetical order
arsort($myarray);
echo "<xmp>arsort(\$myarray);\n";
print_r($myarray);
echo '</xmp>';
//now to sort in alphabetical order by value
asort($myarray);
echo "<xmp>asort(\$myarray);\n";
print_r($myarray);
echo '</xmp>';
?>
The above outputs the below:
arsort($myarray);
Array
(
[1] => sauce
[2] => salt
[0] => orange
[a] => banana
[b] => apple
)
asort($myarray);
Array
(
[b] => apple
[a] => banana
[0] => orange
[2] => salt
[1] => sauce
)
So as you can see, asort has made the array sort alphabetically by value and arsort sorted in reverse order to asort by value while keeping the keys how they should. Also note: DO NOT use the following code as it won't work:
$myarray=array('some','value','being','sorted');
//above is valid but every line below is not
$myarray=arsort($myarray);
$myarray=asort($myarray);
If you assign the variable like the above then it will destroy the array and leave the number 1 as the value. To solve this the following must be used.
$myarray=array('some','value','being','sorted');
//now both the above and below is valid
arsort($myarray);
asort($myarray);
Sorting an array by its key
Sorting an array by its key is exactly like sorting an array by its value except if you have multiple types of keys a special parameter will need to be specified and your replace the first letter in asort and arsort with a k making ksort and krsort. Below is an example
<?php
$myarray=array('b'=>'apple',0=>'orange','a'=>'banana',2=>'salt',1=>'sauce');
//sort in reverse alphabetical order
krsort($myarray, SORT_STRING);
echo "<xmp>krsort(\$myarray, SORT_STRING);\n";
print_r($myarray);
echo '</xmp>';
//now to sort in alphabetical order by value
ksort($myarray, SORT_STRING);
echo "<xmp>ksort(\$myarray, SORT_STRING);\n";
print_r($myarray);
echo '</xmp>';
?>
The above outputs the below:
krsort($myarray, SORT_STRING);
Array
(
[b] => apple
[a] => banana
[2] => salt
[1] => sauce
[0] => orange
)
ksort($myarray, SORT_STRING);
Array
(
[0] => orange
[1] => sauce
[2] => salt
[a] => banana
[b] => apple
)
So as you can see, the array is now sorted by its key Also note: DO NOT use the following code as it won't work:
$myarray=array('some','value','being','sorted');
//above is valid but every line below is not
$myarray=krsort($myarray);
$myarray=ksort($myarray);
If you assign the variable like the above then it will destroy the array and leave the number 1 as the value. To solve this the following must be used.
$myarray=array('some','value','being','sorted');
//now both the above and below is valid
krsort($myarray);
ksort($myarray);
Searching in an array key and value
There are two functions for this job in_array() and array_key_exists() however they can be recourse hungery on huge arrays and should be avoided if possible. The array_key_exists() function can be easily avoided with an alternative function called isset(). Below is an example of how to use the isset function to check if a key exists in the array.
<?php
if (isset($myarray['this_is_the_key'])) {
//pass true
}
//or
if (isset($myarray['another_example'])) {
//pass true
}
?>
And as a general rule of thumb, the more recourses you can save the better and it is the little things that count. As for how to replace the in_array function with something more efficient, the best alternative is the design of your array. So make your values the keys and make the keys the values. Then again use the isset function. Below is an example:
<?php
$myarray=array('apple'=>'apple','orange'=>'orange','banana'=>'banana','salt'=>'salt');
if (isset($myarray['apple'])) {
echo '<xmp>';
print_r($myarray);
echo '</xmp>';
}
?>
The above code will generate the following:
Array
(
[apple] => apple
[orange] => orange
[banana] => banana
[salt] => salt
)
As you can see if you put the variable both in the key and value fields then you can easily search it without having to worry about cpu. This is especially handy for arrays with hundreds of values. But this technique only works when every value is unique. If every value is not unique then you would need to use the following:
<?php
$myarray=array(
'apple'=>true,0=>'apple',
'orange'=>true,1=>'orange',
'banana'=>true,2=>'banana',
'salt'=>true,3=>'salt');
if (isset($myarray['apple'])) {
echo '<xmp>';
print_r($myarray);
echo '</xmp>';
}
?>
The above code will generate the following:
Array
(
[apple] => 1
[0] => apple
[orange] => 1
[1] => orange
[banana] => 1
[2] => banana
[salt] => 1
[3] => salt
)
The above method will use a little more memory but by far less cpu so is worth trading from cpu usage to memory usage as cpu is more frequently used.
