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

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

Версия 10:37, 26 мая 2010

Counting Array Elements

 
<?php
  $dogs = array("A" => "AA", "Bud" => "BB", "C" => "D");
  $birds = array("parrot", "magpie", "lorakeet", "cuckoo");
  printf("<p>There are %d dogs and %d birds.</p>", count($dogs), count($birds));
  $birds[] = "ibis";
  printf("<p>There are %d birds:</p>", count($birds));
  printf("<pre>%s</pre>\n", var_export($birds, TRUE));
  $birds[10] = "heron";
  unset($birds[3]);
  printf("<p>There are %d birds:</p>", count($birds));
  printf("<pre>%s</pre>\n", var_export($birds, TRUE));
?>



Get the size of an array in PHP using the count() function

 
<?php 
    $dogs = array("A" => "C", "B" => "D", "X" => "Z"); 
    
    $birds = array("a", "b", "c", "d"); 
    
    printf("%d dogs and %d birds", count($dogs), count($birds)); 
    
    $birds[] = "i"; 
    printf("%d birds:", count($birds)); 
    printf("%s", var_export($birds, TRUE)); 
    
    
    $birds[10] = "h"; 
    unset($birds[3]); 
    printf("%d birds:", count($birds)); 
    printf("%s", var_export($birds, TRUE)); 
?>



Getting the Number of Lines in a File

 
<?php
  $afile = "data.txt";
  if (file_exists ($afile)){
    $rows = file ($afile);
    echo count ($rows) . " lines in this file"; //Outputs 4 in this case
  } else {
    echo "Sorry, file does not exist.";
  }
  
?>



Using count() to Iterate Through an Array

 
<?php
    $myarray = array("php", "is", "cool");
    for($i = 0; $i < count($myarray); $i++) {
      echo "The value of index $i is: {$myarray[$i]}<BR>\n";
    }
?>