3.PHP Arrays

1. Enumerated Arrays 
Initializing Arrays 
$users =array(“hi”,”hello”,”there”);
or
$users[]=“hi”;
$users[]=“hello”;
$users[]=“there”;
or
$users[1]=“hi”;
$users[2]=“hello”;
$users[3]=“there”;
or 
$users[100]=“hi”;
$users[200]=“hello”;
$users[300]=“there”;

Appending to an Array 
$users =array(“hi”,”hello”,”there”);
$users[] = “John”;


Accessing
$first = $users[0];
$second = $users[1];
$third = $users[2];
$fourth = $users[3];


Looping through
You can use the ordinary loop
or 
foreach($var as $val)
Ex.
foreach($users as $container)
{
print “$container”;
}

2. Associative Arrays 
Initializing
$one_piece = array(
“name”=>”Luffy”,
“power”=>”rubber”,
“profession”=>”pirate”
 );

Accessing
echo $one_piece['name'];


Looping through
foreach($var as $key=>$val)
Ex.
foreach($one_piece as $key=>$content)
{
print “$key: $content”;
}


3. Multi-dimensional Array

Initializing

<?php 

$shop = array( array("rose", 1.25 , 15),
               array("daisy", 0.75 , 25),
               array("orchid", 1.15 , 7) 
             ); 
?>

Accessing
<?php 
echo "<h1>Manual access to each element</h1>";
echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";

echo "<h1>Using loops to display array elements</h1>";
echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    for ($col = 0; $col < 3; $col++)
    {
        echo "<li>".$shop[$row][$col]."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";

4. Array Manipulation Functions
print_r($arr) 
array_merge($arr1, $arr2)
array_push($arr1,1,2,3….)
array_unshift($arr1,1,2,3..)
array_shift($arr1,1,2,3..)
array_slice($arr1,start,number)
sort($arr)
rsort($arr)
asort($arr)
ksort($arr)
array_pad($arr,total_number,’’)

No comments:

Post a Comment