Php length of array

Php length of array

Как узнать длину массива в PHP?

В php нету понятия как length, но есть специальная функция:

int count ( mixed var [, int mode] );

Пример:

$arr[] = 1;
$arr[] = 3;
$arr[] = 5;
$result = count($arr);
// $result == 3

Кстати, чтобы узнать длину строки length тоже не подойдет. Нужно воспользоваться php-функцией strlen().

$my_string = ‘ABCDE’;
$result = strlen($my_string);
// $result == 5

7 комментариев на «Как узнать длину массива в PHP?»

sizeof() работает быстрее

С х** ли она будет быстрее работать, если sizeof() — алиас на count() ?

это вам даст не длину массива а количество строк в массиве, это немного разные вещи

А мне пофиг, я нашел то что искал

$abcdef= array(
‘abc’ => array(‘a’, ‘b’, ‘c’),
‘def’ => array(‘d’, ‘e’, ‘f’));

echo count($abcdef, COUNT_RECURSIVE); // рузультат 8

sizeof() — не работает быстрее, так как sizeof() просто псевдоним функции count();

In PHP, the total number of elements in an array can be calculated by a couple of PHP functions count() and sizeof(), where as the sizeof() is an alias of the master function count(). We are going to see about these functions in this article in detail with suitable examples for calculating PHP array length.

count()

The syntax of PHP count() function is,

array_variable

The array variable is required for which the length will be calculated. If the value of this first argument is not set or having an empty array, then count() will return 0. And, if the variable specified is not an array, then, count method will return 1. To check the state of this variable whether it is not set or it is empty, we can use PHP predefined function, isset() and empty(), respectively.

This argument is optional and has value to specify the mode of operation to be used in calculating array length. There are various possible options to this argument. These are,

  • COUNT_NORMAL – By specifying this predefined constant for the optional second argument of count() function, it will return the length of an array in depth 0.
  • COUNT_RECURSIVE – This value will be used for recursive count operation, till it reaches depth n. This recursive call will be continued infinitely, till it reaches depth n or the program execution time limit is elapsed.

Note:

  • The alternative values can be passed as the value of this optional argument is, 0 and 1 to create the same effect on returning array length with COUNT_NORMAL and COUNT_RECURSIVE, respectively.
  • COUNT_NORMAL is the default option, whereas, if no second argument is specified while invoking count().

Example: PHP count()

The following program is shown as an example for count() function to calculate a number of elements available in a two-dimensional array. Since the input array of this program contains more than one dimensions, we can differentiate the output values return by using various mode of operations.

Читайте также:  Ubuntu server удаленное управление

Let us use the same two-dimensional array we have taken as an example for PHP inheritance article. That is,

Now, we can invoke count() function by passing different possible mode option, as follows,

In the above PHP code, the count() is invoked with normal, default and recursive mode, and the returned values are stored into an array named, $array_length, by specifying the appropriate name indices. The integer value returned as the length of the given input array will be same for the normal and default mode. This will be clear with the following output of this program.

sizeof()

This function is an alias of PHP count() function as we said at the beginning of this article, and accepts the same set of arguments as like as count().

We can replace the count() with sizeof() in the above program to compare the results of both functions which will be same for both functions calls.

Alias functions in PHP are preserved for providing backward compatibility, though it is not good programming practice to use alias functions. Why because, we need to maintain our code with an upgraded version since there is no guarantee for the alias functions will exist for a longer time with the future API clean up.

Particularly, sizeof() function performs differently depends on the programming languages. For example, in C, this function is used to calculate the size of the data type to be represented in bytes. So, the developer who is new for PHP, migrating from C-like languages, will be confused with this function. So, it is preferable to use master functions instead of aliases.

Comments to “PHP Array Length”

Good post. Specially the clarification of why not to use sizeof.
sizeof should be mentioned as not recommended on the PHP documentation page and gradually deprecated. I have seen some applications that use or prefer sizeof instead of count.

(PHP 4, PHP 5, PHP 7)

count — Count all elements in an array, or something in an object

Description

Counts all elements in an array, or something in an object.

For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count() , which returns the return value for the count() function.

Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.

Parameters

An array or Countable object.

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.

Читайте также:  Ddr4 32 ggb 3000 mhz corsair

count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected.

Return Values

Returns the number of elements in array_or_countable . When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL , will be returned.

Examples

Example #1 count() example

[ 0 ] = 1 ;
$a [ 1 ] = 3 ;
$a [ 2 ] = 5 ;
var_dump ( count ( $a ));

$b [ 0 ] = 7 ;
$b [ 5 ] = 9 ;
$b [ 10 ] = 11 ;
var_dump ( count ( $b ));

var_dump ( count ( null ));

var_dump ( count ( false ));
?>

The above example will output:

Example #2 Recursive count() example

= array( ‘fruits’ => array( ‘orange’ , ‘banana’ , ‘apple’ ),
‘veggie’ => array( ‘carrot’ , ‘collard’ , ‘pea’ ));

// recursive count
echo count ( $food , COUNT_RECURSIVE ); // output 8

// normal count
echo count ( $food ); // output 2

Changelog

Version Description
7.2.0 count() will now yield a warning on inval >array_or_countable parameter.

See Also

  • is_array() — Finds whether a variable is an array
  • isset() — Determine if a variable is declared and is different than NULL
  • empty() — Determine whether a variable is empty
  • strlen() — Get string length
  • is_countable() — Verify that the contents of a variable is a countable value

User Contributed Notes 14 notes

[Editor’s note: array at from dot pl had pointed out that count() is a cheap operation; however, there’s still the function call overhead.]

If you want to run through large arrays don’t use count() function in the loops , its a over head in performance, copy the count() value into a variable and use that value in loops for a better performance.

to end the debate: count() is the same as empty()

test code below:

results on my computer:

count : double(0.81396999359131)
empty : double(0.81621310710907)

using isset($test[0]) is a bit slower than empty;
test without adding value to the array in function ****Test: still the same.

function average (array $test )
<
$sum = 0 ;
foreach( $test as $value ) <
$sum += $value ;
>

function countTest (array $test )
<
$i = 0 ;
while ( $i ++ 1000000 ) <
count ( $test );
$test [ "lol $i " ] = "teset $i " ;
>
>

function emptyTest (array $test )
<
$i = 0 ;
while ( $i ++ 1000000 ) <
empty( $test );
$test [ "lol $i " ] = "teset $i " ;
>
>

$test = [];
$i = 0 ;
while ( $i ++ 20000000 ) <
$test [] = $i ;
>

$j = 10 ;
$value = $j ;
$count = [];
$isEmpty = [];
while ( $j —) <
$time = microtime ( true );
countTest ( $test );
$count [] = microtime ( true ) — $time ;

$time = microtime ( true );
emptyTest ( $test );
$isEmpty [] = microtime ( true ) — $time ;
>

Читайте также:  Fallout 4 создание брони

var_dump ( average ( $count ) / $value );
var_dump ( average ( $isEmpty ) / $value );

If you are on PHP 7.2+, you need to be aware of "Changelog" and use something like this:

= is_array ( $countFruits ) || $countFruits instanceof Countable ? count ( $countFruits ) : 0 ;
?>

You can organize your code to ensure that the variable is an array, or you can extend the Countable so that you don’t have to do this check.

My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).

function getArrCount ( $arr , $depth = 1 ) <
if (! is_array ( $arr ) || ! $depth ) return 0 ;

$res = count ( $arr );

foreach ( $arr as $in_ar )
$res += getArrCount ( $in_ar , $depth — 1 );

You can not get collect sub array count when there is only one sub array in an array:

$a = array ( array (‘a’,’b’,’c’,’d’));
$b = array ( array (‘a’,’b’,’c’,’d’), array (‘e’,’f’,’g’,’h’));

echo count($a); // 4 NOT 1, expect 1
echo count($b); // 2, expected

I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.

// $limit is set to the number of recursions
function count_recursive ( $array , $limit ) <
$count = 0 ;
foreach ( $array as $id => $_array ) <
if ( is_array ( $_array ) && $limit > 0 ) <
$count += count_recursive ( $_array , $limit — 1 );
> else <
$count += 1 ;
>
>
return $count ;
>
?>

All the previous recursive count solutions with $depth option would not avoid infinite loops in case the array contains itself more than once.
Here’s a working solution:

/**
* Recursively count elements in an array. Behaves exactly the same as native
* count() function with the $depth option. Meaning it will also add +1 to the
* total count, for the parent element, and not only counting its children.
* @param $arr
* @param int $depth
* @param int $i (internal)
* @return int
*/
public static function countRecursive (& $arr , $depth = 0 , $i = 0 ) <
$i ++;
/**
* In case the depth is 0, use the native count function
*/
if (empty( $depth )) <
return count ( $arr , COUNT_RECURSIVE );
>
$count = 0 ;
/**
* This can occur only the first time when the method is called and $arr is not an array
*/
if (! is_array ( $arr )) <
return count ( $arr );
>

// if this key is present, it means you already walked this array
if (isset( $arr [ ‘__been_here’ ])) <
return 0 ;
>

$arr [ ‘__been_here’ ] = true ;

// you need to unset it when done because you’re working with a reference.
unset( $arr [ ‘__been_here’ ]);
return $count ;
>
?>

Ссылка на основную публикацию
Adblock detector