PHP/Data Structure/count
Содержание
Counting Array Elements
<source lang="html4strict">
<?php
$dogs = array("A" => "AA", "Bud" => "BB", "C" => "D"); $birds = array("parrot", "magpie", "lorakeet", "cuckoo");printf("
There are %d dogs and %d birds.
", count($dogs), count($birds));$birds[] = "ibis";printf("
There are %d birds:
", count($birds)); printf("%s\n", var_export($birds, TRUE));
$birds[10] = "heron"; unset($birds[3]);printf("
There are %d birds:
", count($birds)); printf("%s\n", var_export($birds, TRUE));
?>
</source>
Get the size of an array in PHP using the count() function
<source lang="html4strict">
<?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));
?>
</source>
Getting the Number of Lines in a File
<source lang="html4strict">
<?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."; }
?>
</source>
Using count() to Iterate Through an Array
<source lang="html4strict">
<?php
$myarray = array("php", "is", "cool"); for($i = 0; $i < count($myarray); $i++) { echo "The value of index $i is: {$myarray[$i]}
\n"; }
?>
</source>