Associative Arrays in PHP

Unknown Reply 8:38 AM
PHP supports a plethora of data types and associative arrays are a very convenient way to represent data collections that may not use numerical keys. This article will provide an overview of the fundamental concepts related to using associative arrays in PHP.

Creating an associative array

There are two ways to create a new array in PHP. You can explicitly create one using the arrayconstruct like so :
$lifespan = array('beaver'=>20);
The second way to create an array is to allow PHP to do it for us automatically, without using thearray construct. We only need to define the first element in the array. The following code creates the same array as the above code :
$lifespan['beaver'] = 20;
We can add as many additional elements to the array as we like. Simply continue along in the same manner. PHP will automatically increase the array’s internal pointer after the definition of each element.
$lifespan['rabbit'] = 10;
$lifespan['beaver'] = 20;
$lifespan['moose'] = 20;
$lifespan['squirrel'] = 6;
$lifespan['weasel'] = 10;
$lifespan['mouse'] = 2;
PHP is very flexible and there are often many ways to accomplish the same task. Here is another way in which we can define the exact same array as above. It accomplishes this using 33 fewer characters and saves a little typing.
$lifespan = array(
  'rabbit'=> 10,
  'beaver'=> 20,
  'moose'=> 20,
  'squirrel'=> 6,
  'weasel'=> 10,
  'mouse'=> 2
);
Both of these ways to create and define arrays are equally valid and largely a manner of coding style or taste. PHP often has multiple ways of accomplishing the same task.

Accessing array elements directly

In order to retrieve a single item’s value from our array we only need to refer to the item’s key. As an example, the code below will display the average lifespan of a squirrel. Next we will look into more convenient ways of accessing all of our array elements using different types of loops.
echo $lifespan['squirrel'];

Using foreach to iterate through array elements

PHP’s foreach looping construct makes it easy to iterate through all of our newly created array elements. As you can see in the code below, there are 3 different parameters we must specify. First is the array that we want to use, followed by variables that will represent the key and valueof each array element.
foreach ($lifespan as $key => $value) {
 echo $key . " : " . $value . "<br />";
}
Numerical arrays have numeric keys. Associative arrays can also use strings as keys as we have done. Here is the output from the above code :
rabbit : 10
beaver : 20
moose : 20
squirrel : 6
weasel : 10
mouse : 2
The $key and $value variables can be given more suitable names. For example, we could use $animal and $years instead of $key and $value. This would produce exactly the same output as the code above and yet it would make for source code which is easier to understand.
foreach ($lifespan as $animal => $years) {
 echo $animal . ' : ' . $years . '<br />';
}
Though the names of the variables have changed, they are still being used as a key associated with a value. You can think of => as pointing a key to a value.
Associative Arrays in PHP

Using a while loop and the each construct to iterate through an array

Another way to iterate through an array is to use a while loop combined with PHP’s eachconstruct. The code below demonstrates this and yet again produces exactly the same output :
while($element = each($lifespan)) {
 echo $element['key'] . ' : ';
 echo $element['value'] . '<br />';
}
As an alternative to $element['key'] and $element['value'], PHP also allows you to use $element[0] and $element[1] for the same purpose.
It is common practise to use PHP’s list construct in conjunction with each. This allows us to return to more suitable variable names as we did in the foreach example above.
reset ($lifespan);
while (list($animal, $years) = each($lifespan)) {
 echo $animal . ' : ' . $years . '<br />';
}
Notice the presence of the reset function. This will set the internal pointer of an array back to its first element. Basically it rewinds us back to the first item in the array. It is only needed when you have iterated through an array and need to do so again. Without using reset, the internal array pointer would otherwise point to the end of the array and not return any further elements.

Manually stepping through an array

As you can see, PHP provides many ways to access array elements. Yet another technique is to manually iterate through all of the elements in an array. The code below produces, once again, the exact same output as the various examples above do.
reset ($lifespan);
$element = each($lifespan);
echo $element[0] . ' : ' . $element[1] . '<br />';
$element = each($lifespan);
echo $element[0] . ' : ' . $element[1] . '<br />';
$element = each($lifespan);
echo $element[0] . ' : ' . $element[1] . '<br />';
$element = each($lifespan);
echo $element[0] . ' : ' . $element[1] . '<br />';
$element = each($lifespan);
echo $element[0] . ' : ' . $element[1] . '<br />';
$element = each($lifespan);
echo $element[0] . ' : ' . $element[1] . '<br />';
After resetting our array back to it’s first element we then begin the manual iteration process. Every time we call the each() function we get the current array element and the array’s internal pointer is incremented by one.
Another way to manually iterate through array elements is to use PHP’s current()next(),prev() and end() functions. These various functions (along with the reset() function) enable you to adjust an array’s internal pointer. Here is another example that produces the exact same output as all of the examples above using this technique.
reset($lifespan);
$element = current($lifespan);
echo key($lifespan) . ' : ' . $element . '<br />';
$element = next($lifespan);
echo key($lifespan) . ' : ' . $element . '<br />';
$element = next($lifespan);
echo key($lifespan) . ' : ' . $element . '<br />';
$element = next($lifespan);
echo key($lifespan) . ' : ' . $element . '<br />';
$element = next($lifespan);
echo key($lifespan) . ' : ' . $element . '<br />';
$element = next($lifespan);
echo key($lifespan) . ' : ' . $element . '<br />';
The key() function will return the key of the element that the array’s internal pointer is currently pointing to. The current() function returns the value of the current array element. In this case it is the very first element of our array.
The next() function performs exactly the same as the current() function except that it advances the internal array pointer by one. Using next() successively (as is done above) allows us to manually iterate through all of the elements in our array.

Sorting array elements

Below are four different functions that PHP provides to help us sort our associative arrays in a variety of ways. PHP has several other sorting functions but we will be focusing on these four to keep things as simple as possible. All of these functions maintain key and value relationships.
FunctionSorts ByOrder of Sort
asortvaluelow to high
arsortvaluehigh to low
ksortkeylow to high
krsortkeyhigh to low
The asort() and arsort() functions sort array elements by their respective values. In order to display the animals with the lowest life expectancy to the highest life expectancy we would useasort(). If instead we wanted the array elements sorted from the highest life expectancy to the lowest we would use arsort().
The ksort() and krsort() functions sort an array’s elements by their keys. The example below displays the animals alphabetically sorted by their keys.
$lifespan = array(
  'rabbit'=> 10,
  'beaver'=> 20,
  'moose'=> 20,
  'squirrel'=> 6,
  'weasel'=> 10,
  'mouse'=> 2
);

ksort($lifespan);

foreach ($lifespan as $key => $value) {
 echo $key . ' : ' . $value . '<br />';
}
Here is the sorted output :
beaver : 20
moose : 20
mouse : 2
rabbit : 10
squirrel : 6
weasel : 10
The r in the arsort() and krsort() function names simply stands for reverse. These functions will sort values from high to low.

Nested associative arrays

It is possible to have arrays within arrays. These are known as nested arrays. If we wanted to add more data fields to our animals we could do so by using nested arrays. The code below adds a weight field to each of our different animals.
$animal = array(
 'rabbit' => array('lifespan'=>10, 'weight'=>1),
 'beaver' => array('lifespan'=>20, 'weight'=>45),
 'moose' => array('lifespan'=>20, 'weight'=>1400),
 'squirrel' => array('lifespan'=>6, 'weight'=>1),
 'weasel' => array('lifespan'=>10, 'weight'=>0.5),
 'mouse' => array('lifespan'=>2, 'weight'=>0.05)
);

foreach ($animal as $key => $value) {
 echo $key . ' :';
 foreach ($value as $k => $v) {
  echo ' ' . $k . '(' . $v . ')';
 }
 echo '<br />';
}
In order to access the fields within our nested array, we could use a nested foreach as is done in the code above. This will access any number of extra fields that we have defined. Here is the generated output of the code :
rabbit : lifespan(10) weight(1)
beaver : lifespan(20) weight(45)
moose : lifespan(20) weight(1400)
squirrel : lifespan(6) weight(1)
weasel : lifespan(10) weight(0.5)
mouse : lifespan(2) weight(0.05)
There is a more readable way of achieving this however. If we know ahead of time the fields that we have, we can request them specifically. For example let’s say that we wanted to list just the weight of all the animals.
foreach ($animal as $key => $value) {
 echo $key . ' :' . $value['weight'] . '<br />';
}
If we wanted just the weight of a moose we could obtain it like so :
echo $animal['moose']['weight'];

Conclusion

PHP has nearly 80 different functions which work with arrays. In this article we have only scratched the surface of some of the fundamentals regarding associative arrays in PHP. Hopefully this is enough to get you started with associative arrays or provides for a refresher in case it’s been a while.
Source : http://computingvoyage.com/1062/associative-arrays-in-php/

Related Posts

PHP 1289413503481487747
Comments
0 Comments
Facebook Comments by Media Blogger

Post a Comment

Search

Ikuti Channel Youtube Aku Yaa.. Jangan Lupa di subscribe. Terima kasih.

Popular Posts

Translate