PHP/Data Structure/Array Index — различия между версиями

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

Текущая версия на 07:02, 26 мая 2010

Adding elements with []

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



Alternating table row colors

 
<?
$row_color = array("red","green");
$color_index = 0;
$meal = array("breakfast" => "A",
              "lunch" => "B",
              "snack" => "C",
              "dinner" => "D");
print "<table>\n";
foreach ($meal as $key => $value) {
    print "<tr bgcolor="" . $row_color[$color_index] . "">";
    print "<td>$key</td><td>$value</td></tr>\n";
    $color_index = 1 - $color_index;
}
print "</table>";
?>



Getting array size

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



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

 
<?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";
}
?>



Setting an Array"s Size

 
<?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("<p>Pups:</p><pre>%s</pre>\n", var_export($pups, TRUE));
  printf("<p>More birds:</p><pre>%s</pre>\n", var_export($more_birds, TRUE));
  $pups = array_pad($dogs, -6, "mutt");
  $more_birds = array_pad($birds, -6, "some bird");
  printf("<p>Pups:</p><pre>%s</pre>\n", var_export($pups, TRUE));
  printf("<p>More birds:</p><pre>%s</pre>\n", var_export($more_birds, TRUE));
  printf("<p>Dogs:</p><pre>%s</pre>\n", var_export($dogs, TRUE));
  printf("<p>Birds:</p><pre>%s</pre>\n", var_export($birds, TRUE));
?>