A Study in Arrays (page 2)
<?php
function prufff ($txt, $size = 3)
{
print "<p><font color=\"0000aa\" size=\"$size\">$txt</font></p>";
}
$robots_spec = array ( name=>"Data", occupation=>"Starfleet Officer", age=>"Unknown",special-power=>"Rapid thinking");
prufff ("The value of \$robots_spec[name] is: $robots_spec[name].");
prufff ("The value of \$robots_spec[occupation] is: ".$robots_spec[occupation].".");
?>
Running the script will give you this:
The value of $robots_spec[name] is: Data.
The value of $robots_spec[occupation] is: Starfleet Officer.
There is more we can do with those complicated associative arrays. See, we can use them as multidimensional arrays, like this:
$robots_spec2 = array (
array(name=>"Data", occupation=>"Starfleet Officer", age=>"Unknown",
special-power=>"Rapid thinking"),
array(name=>"Mazinger", occupation=>"Japan's Savior", age=>"Thirty",
special-power=>"Lots of weapons"),
array(name=>"Sonny", occupation=>"Household Robot ", age=>"5",
special-power=>"Sentient Being")
);
In this case, we have three robots: Data from Star Trek, Sonny from I Robot, and the not-so popular Mazinger from Japanese anime of the late 70s. This is a multidimensional array. Let's try a script using this array:
<?php
function pruw ($txt, $size = 3)
{
print "<p><font color=\"0000aa\" size=\"$size\">$txt</font></p>";
}
function pruw2 ($txt, $size = 3)
{
print "<p><font color=\"ff0000\" size=\"$size\">$txt</font></p>";
}
$robots_spec2 = array (
array ( name=>"bob",
occupation=>"superhero",
age=>30,
specialty=>"x-ray vision" ),
array ( name=>"sally",
occupation=>"superhero",
age=>24,
specialty=>"superhuman strength" ),
array ( name=>"mary",
occupation=>"arch villain",
age=>63,
specialty=>"nanotechnology" )
);
pruw ("The value of \$robots_spec2[1][name] is:". $robots_spec2[0][name].".");
pruw ("The value of \$robots_spec2[2][occupation] is: ".$robots_spec2[1][occupation].".");
Notice the warning given to you inside the script. The output of this script will be:
The value of $robots_spec2[1][name] is:bob.
The value of $robots_spec2[2][occupation] is: superhero.
Warning, one thing about statements like $robots_spec2[1][occupation] is that when you use them with print or echo, make sure they are outside the "" of print. Otherwise, you may end up with no output. Multidimensional arrays can cause small problems when mixed with print or echo.
That's all for now. But arrays are a broad topic, so expect a part of this tutorial.



