|
 |
count (PHP 3, PHP 4, PHP 5) count -- Посчитать количество элементов массива или количество свойств объекта Описаниеint count ( mixed var [, int mode] )
Возвратить количество элементов переменной var,
которая обычно является array, или любым другим объектом, который может
содержать хотя бы один элемент.
Для объектов count() возвращает количество нестатических
свойств, не принимая во внимание видимость. Если у вас включена поддержка
SPL, вы можете перехватить
count(), реализуя интерфейс
Countable. Этот интерфейс имеет только один метод,
count(), который возвращает значение функции
count().
Если var не является массивом или объектом,
реализующим интерфейс Countable,
будет возвращена 1.
За одним исключением: если var - NULL,
то будет возвращён 0.
Замечание:
Дополнительный параметр mode был добавлен начиная с
PHP 4.2.0.
Если дополнительный параметр mode установлен в
COUNT_RECURSIVE (или 1), count()
будет считать количество элементов массива рекурсивно. Это особенно полезно для подсчёта
всех элементов многомерных массивов. Предустановленное значение
параметра mode - 0.
count() не обнаруживает бесконечную рекурсию.
Предостережение |
count() может возвратить 0 для переменных, которые
не установлены, но также может возвратить 0 для переменных, которые
инициализированы пустым массивом. Используйте функцию
isset() для того, чтобы протестировать, установлена ли переменная.
|
Пожалуйста, см. раздел этого руководства Array
для того, чтобы получить детальное представление о реализации и использовании
массивов в PHP.
Пример 1. Пример использования count()
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b);
$result = count(null);
$result = count(false);
?>
|
|
Пример 2.
Пример рекурсивного использования count() (PHP >= 4.2.0)
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
echo count($food, COUNT_RECURSIVE); echo count($food); ?>
|
|
См. также is_array(),
isset() и
strlen().
count
anil dot iitk at gmail dot com
26-Jan-2006 12:32
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));
echo "<br>".count($food, COUNT_RECURSIVE); function average($a){
return array_sum($a)/count($a) ;
}
$b = array(1,2,3,4,5,6,7,8,9);
echo "Average of array:".average($b);
?>
Scorch at netpix dot com
20-Dec-2005 05:59
Be careful of recasting your variables, especially with database array returns:
<?php
$res = mysql_query("select * from blah") $row = mysql_fetch_array($res); echo count($row); echo $row[0]; echo count($row); ?>
Tom
30-Nov-2005 04:57
You can find an average from an array using this and array_sum.
<?php
function average($input) {
return array_sum($input) / count($input);
}
?>
You can also do a method of form validation that involves putting all errors into an array and letting count() do the key part.
<?php
if(isset($_POST['submit'])) {
$errors = array();
if(empty($_POST['message'])) $errors[] = "Empty message field";
if(!preg_match('/[a-z0-9.]@[a-z0-9].[a-z]/i', $_POST['email']) {
$errors[] = "Bad email address";
}
if(count($errors) == 0) {
}
}
?>
NOSPAM at NOSPAM dot com
09-Nov-2005 07:18
markis dot brachel at ntlworld dot com had a slight error in his comments that may confuse people.
<?
$holes = array ("first", 2 => "second", 5 => "fifth", "sixth");
$array_count = count($holes);
for($y=0; $y<$array_count; $y++) {
if(isset($holes[$y])) {
echo($holes[$y]);
}
else { $array_count++; }
}
?>
It says:
Note blank entries 3 and 4
But entry 1 is blank too ("first" 's key=0, "second" 's key=2, 1 is missing also, array starts at 0 by default)
Fred D
18-Oct-2005 09:16
The trim_text function was helpful, but it did not take account of the possibility of having nothing to trim which can sometimes happen if you are using this function in a loop through data. I've added a count function to deal with that possibility
------------------------------
function trim_text_elipse($text, $count){
//Create variable
$trimmed="";
//Remove double white space
$text = str_replace(" ", " ", $text);
//Turn the text into an array
$string = explode(" ", $text);
//Check to see how many words there are
$wordTotal = count($string);
//Check to see if there are more words than the $count variable
if($wordTotal > $count){
//Loop through adding words until the $count variable is reached
for ( $wordCounter = 0; $wordCounter <= $count; $wordCounter++ ){
$trimmed .= $string[$wordCounter];
//Check to and add space or finish with elipse
if ( $wordCounter < $count ){ $trimmed .= " "; }
else { $trimmed .= " …"; }
}
}else{
//Set value returned to the existing value
$trimmed =$text;
}
//Trim off any white space
$trimmed = trim($trimmed);
return $trimmed;
}
-------------------------------
david _at_ webgroup _dot_ org
12-Feb-2005 04:30
While michael at htmlland dot net's code works, I believe it is better to use:
$extension=substr($file,strrpos($file,".")+1);
This doesn't incur the overhead of array handling. I haven't tested it for time functions, but it should work just as well and SHOULD be faster.
freefaler at gmail dot com
19-Nov-2004 05:01
If you want to count only elements in the second level of 2D arrays.A close to mind note, useful for multidimentional arrays:
<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard','pea'));
echo count($food,COUNT_RECURSIVE); echo count($food); echo (count($food,COUNT_RECURSIVE)-count($food,0)); ?>
moazzam at ummah dot org
14-Oct-2004 04:59
This is an obvious note, but I am writing it any way so other, who did may not have observed this, can take advantage of it too.
When running loops with count conditions, the code runs faster if you first assign the count() value to a variable and use that (instead of using count() directly in a loop condition.
To explain my point better, here is an example:
<?php
for ($i=0; $i<10000; $i++) {
$arr[] = $i;
}
$time11 = microtime_float();
$bf = "";
for ($i=0; $i<count($arr); $i++) {
$bf .= $arr[$i]."\n";
}
$time12 = microtime_float();
$time1 = $time12 - $time11;
print "First: ".$time1."\n";
$time21 = microtime_float();
$l = count($arr);
for ($i=0; $i<$l; $i++) {
$bf .= $arr[$i]."\n";
}
$time22 = microtime_float();
$time2 = $time22 - $time21;
print "Second: ".$time2."\n";
?>
The output from the code above is (when run many times):
First: 0.13001585006714
Second: 0.099159002304077
First: 0.12128901481628
Second: 0.079941987991333
First: 0.18690299987793
Second: 0.13346600532532
As you can see, the second method (which doesnt use count() directly in the loop) is faster than the first method (which uses count() directly in the loop).
BTW: I copied the microtime_float() function from one of the comments in the microtime() section. It just returns time with microseconds as float. Check comments in microtime() for more info.
michael at htmlland dot net
04-Jun-2004 10:30
I have found on upload scripts or on file manipulation scripts that people can trick a classic file type filter:
example:
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[1];
if($extention == "jpg"){ echo"Not correct"; exit; }
This returns the filename extention as jpg not wav.
One way to change this is to use count() :
example:
$filename="bob.jpg.wav";
$bits= explode(".",$filename);
$extention= $bits[count($bits) - 1];
if($extention == "jpg"){ echo"Not correct"; exit; }
This returns the filename extention as wav not jpg.
rolandfoxx at yahoo dot com
30-Mar-2004 04:13
As an addition, any of the array manipulation functions can likewise get count to once again return 0:
<?php
$a = array();
print(count($a)); $a[0] = "foo";
array_shift($a);
print(count($a)); $a[0] = "bar";
array_splice($a, 0, 1);
print(count($a)); ?>
admin at lft-muenchen dot de
12-Mar-2003 04:18
Note:
print (strlen($a)); // will print 0
$a="";
print (strlen($a)); // will print 1
$a=null;
print (strlen($a)); // will print 1
$a=array();
print (strlen($a)); // will print 0
you can only get an array back to size 0 by using the array() command, not by just setting it to "" or null.
simon at invalid dot com
20-Aug-2002 12:40
Reminder for using count():
<?php
$ary = array(null, "a", "b", null);
echo count($ary); $ary[10] = "c";
echo count($ary); $ary[15] = null;
echo count($ary); ?>
=> NULL is seen as an element in count()
Count 2D array:
<?php
$a2Dary = array(array("a", "b") , array(), "v");
echo count($a2Dary); echo count($a2Dary[0]); echo count($a2Dary[1]); echo count($a2Dary[2]); ?>
Hope can help you
bryce at obviously dot com
22-Jul-2002 03:44
If you're working with a database, you'll probably have much greater luck with: mysql_num_rows( $result );
08-Jul-2002 09:18
Perhaps change the wording of this description from "Count elements in a variable" to "Count total elements in a variable" as it may be interpreted (by me) as a function for counting specific elements (ie, number of substrings)
webmaster at NOSPAMtrafficg dot com
26-Apr-2002 03:48
Counting a multi-dimentional array
test array
<?php
$settings[0][0] = 128;
$settings[0][1] = 256;
$settings[0][2] = 384;
$settings[0][3] = 512;
$settings[0][4] = 1024;
$settings[0][5] = 2048;
$settings[1][0] = 1024;
$settings[1][1] = 2048;
$settings[1][2] = 3072;
$settings[1][3] = 4096;
count($settings) count($settings[0]) count($settings[1]) ?>
markis dot brachel at ntlworld dot com
12-Apr-2002 05:25
Someone said you couldn't use the for loop and count array command for processing arrays with missing entries.
Well, heres my working idea:
<?
$holes = array ("first", 2 => "second", 5 => "fifth", "sixth");
$array_count = count($holes);
for($y=0; $y<$array_count; $y++) {
if(isset($holes[$y])) {
echo($holes[$y]);
}
else { $array_count++; }
}
?>
kanareykin at denison dot edu
26-Mar-2001 01:13
Here's how to count non-empty elements
in an array of any dimension. Hope
it will be useful for somebody.
<?php
function count_all($arg)
{
if ($arg) {
if(!is_array($arg))
return 1;
foreach($arg as $key => $val)
$count += count_all($val);
return $count;
}
}
?>
martin at complinet dot com
30-Nov-2000 04:31
The count function does not ignore null values in an array. To achieve this use this function.
<?php
function xcount($array) {
while (list($key, $value) = each($array)) {
if ($value) {
$count++;
}
}
return $count;
}
?>
admin at serverbase dot com
02-Oct-2000 11:24
Be carefull with count when using in a while (list()=each()) construct, count changes the internal array pointer and strange things will happen :-)
jmcastagnetto at php dot net
04-Sep-2000 12:30
If you want to disambiguate if a variable contains an array w/ only one element, just us is_array() or gettype()
legobuff at hotmail dot com
02-Feb-2000 10:43
This is taken from sganer@expio.co.nz comments on the sizeof() function:
If some elements in your array are not set, then sizeof() and count() will not return the index of the last element, but will return the number of set elements. To find the index of the last element in the array:
end($yourArray);
$index = key($yourArray);
... Where $yourArray is the array you want to find the last index ($index) of.
chopin at csone dot kaist dot ac dot kr
25-Aug-1999 03:13
sizeof(), count() function is for only array not string data type.
ex) $str = "abcd";
echo $str[3] ; // string indexing like array
echo sizeof(str); // return 1 always
dmb27 at cornell dot edu
30-Jun-1999 01:53
Be careful of recasting your variables, especially with database array returns:
<?php
$res = mysql_query("select * from blah") $row = mysql_fetch_array($res); echo count($row); echo $row[0]; echo count($row); ?>
| |