PHP/Data Structure/Array Index

Материал из Web эксперт
Перейти к: навигация, поиск

Adding elements with []

   <source lang="html4strict">

<? // This sets $lunch[0] $lunch[] = "A"; // This sets $lunch[1] $lunch[] = "B"; $dinner = array("A", "B","C"); // This sets $dinner[3] $dinner[] = "F"; ?>

 </source>
   
  


Alternating table row colors

   <source lang="html4strict">

<? $row_color = array("red","green"); $color_index = 0; $meal = array("breakfast" => "A",

             "lunch" => "B",
             "snack" => "C",
             "dinner" => "D");
print "\n"; foreach ($meal as $key => $value) { print ""; print "\n";
   $color_index = 1 - $color_index;

}

print "
$key$value
";

?>

 </source>
   
  


Getting array size

   <source lang="html4strict">

<html>

<head>
 <title>Getting array size</title>
</head>
<body> 
    <?php $arr = array(); for( $i = 0; $i < 3; $i++ ) { $arr[ $i ] ="
  • This is element $i
  • ";
     }
     foreach( $arr as $value )
     {
       echo($value);
     }
     $size = count( $arr );
    
    echo( "
  • Total number of elements is $size
  • " );
     ?>
    
</body>

</html>

 </source>
   
  


Loops through an indexed array of fruit names and creates a new array with the count of each fruit name.

   <source lang="html4strict">

<?php $fruits = array("apple", "orange", "orange"); $fruit_count = array(); foreach ($fruits as $i=>$fruit) {

 @$fruit_count[$fruit]++;

} asort($fruit_count); foreach ($fruit_count as $fruit=>$count) {

 echo "$fruit = $count\n";

} ?>

 </source>
   
  


Setting an Array"s Size

   <source lang="html4strict">

<?php

 $dogs = array("A" => "AA", "Bud" => "BB","C" => "D");
 $birds = array("parrot", "magpie", "lorakeet", "cuckoo");
 $pups = array_pad($dogs, 6, "mutt");
 $more_birds = array_pad($birds, 6, "some bird");
printf("

Pups:

%s
\n", var_export($pups, TRUE)); printf("

More birds:

%s
\n", var_export($more_birds, TRUE));
 $pups = array_pad($dogs, -6, "mutt");
 $more_birds = array_pad($birds, -6, "some bird");
printf("

Pups:

%s
\n", var_export($pups, TRUE)); printf("

More birds:

%s
\n", var_export($more_birds, TRUE)); printf("

Dogs:

%s
\n", var_export($dogs, TRUE)); printf("

Birds:

%s
\n", var_export($birds, TRUE));

?>

 </source>