For php count array

Array Length PHP Calculate PHP Array Length

How to calculate the PHP array length? If you want to count the total number of elements or values in an array, you can easily do it by using PHP inbuilt functions called count() or sizeof(). You can find a detailed explanation with the example below that how you can calculate PHP array length.

count(): PHP Array Length For Loop

count(var array_or_countable, mode)

If you don’t know what is an array then please see the detailed explanation of how arrays are created and used in PHP.

array_or_countable

The first argument is an array variable that is required to calculate the PHP array length. If the first argument is empty, an empty array or not set, then count() function will return 0. And, If the variable is specified but its data type is not an array, then, count() function will return 1. To avoid this, you can use the PHP inbuilt function isset() and check whether an array variable is set or not.

mode

The second argument is optional and can take two values either COUNT_NORMAL or COUNT_RECURSIVE. You can pass the value 0 and 1 instead of COUNT_NORMAL and COUNT_RECURSIVE that will make the same effect. The default value of the second argument is COUNT_NORMAL if no value passed as the second argument. Example #1 count() example

$food = 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); or count($food, COUNT_NORMAL ); // output 2

In the above code block, We have created a multidimensional array. When we use count function in the RECURSIVE mode as a second argument, Output is 8. And, when we use count function in the NORMAL mode as a second argument or default mode, Output is 2.

sizeof()— PHP Array Length?

sizeof() is an alias of PHP count() function and accepts the same arguments as count(). If We replace the count() with sizeof() in the above example, the results of both functions will be the same for both functions calls. Many programmers who come from C language background expect sizeof() to return the amount of memory allocated. But, sizeof() — as described above — is an alias for count() in PHP. It is advised to always use count() instead of sizeof(). Because there is no guarantee for the alias function if they will exist or not in a future upgrade. So, you should always consider to maintain code standard as well as avoid to break the application due to the upgraded version.

Читайте также:  Изменить размер select html

Источник

For php count array

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3) statement

The first expression ( expr1 ) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to true , the loop continues and the nested statement(s) are executed. If it evaluates to false , the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2 , all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as true , like C). This may not be as useless as you might think, since often you’d want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

for ( $i = 1 ; ; $i ++) if ( $i > 10 ) break;
>
echo $i ;
>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate «colon syntax» for for loops.

for (expr1; expr2; expr3): statement . endfor;

It’s a common thing to many users to iterate through arrays like in the example below.

/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = array(
array( ‘name’ => ‘Kalle’ , ‘salt’ => 856412 ),
array( ‘name’ => ‘Pierre’ , ‘salt’ => 215863 )
);

Читайте также:  Python decompiler online exe

for( $i = 0 ; $i < count ( $people ); ++ $i ) $people [ $i ][ 'salt' ] = mt_rand ( 000000 , 999999 );
>
?>

The above code can be slow, because the array size is fetched on every iteration. Since the size never changes, the loop be easily optimized by using an intermediate variable to store the size instead of repeatedly calling count() :

$people = array(
array( ‘name’ => ‘Kalle’ , ‘salt’ => 856412 ),
array( ‘name’ => ‘Pierre’ , ‘salt’ => 215863 )
);

for( $i = 0 , $size = count ( $people ); $i < $size ; ++ $i ) $people [ $i ][ 'salt' ] = mt_rand ( 000000 , 999999 );
>
?>

User Contributed Notes 19 notes

Looping through letters is possible. I’m amazed at how few people know that.

returns: R S T U V W X Y Z AA AB AC

Take note that you can’t use $col < 'AD'. It only works with !=
Very convenient when working with excel columns.

The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn’t change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

$maxI = somewhat_calcMax ();
for ( $i = 0 ; $i somewhat_doSomethingWith ( $i );
>
?>

And here a little trick:

$maxI = somewhat_calcMax ();
for ( $i = 0 ; $i ?>

The $i gets changed after the copy for the function (post-increment).

You can use strtotime with for loops to loop through dates

Remember that for-loops don’t always need to go ‘forwards’. For example, let’s say I have the following code:

As other comments have pointed out , if «calculateLoopLength» will keep giving back the same value , it can be moved outside the loop :

$loopLength = calculateLoopLength ();
for ( $i = 0 ; $i < $loopLength ; $i ++) doSomethingWith ( $i );
>
?>

However, if the order the looping doesn’t matter (ie. each iteration is independent) then we don’t need to use an extra variable either, we can just count down (ie. loop ‘backwards’) instead:

for ( $i = calculateLoopLength (); $i > 0 ; $i —) doSomething ( $i );
>
?>

In fact, we can simplify this even more, since «$i > 0» is equivalent to «$i» (due to type casting):

for ( $i = calculateLoopLength (); $i ; $i —) doSomething ( $i );
>
?>

Читайте также:  Using ascii in java

Finally, we can switch to a ‘pre-decrement’ instead of a ‘post-decrement’ to be slightly more efficient (see, for example, http://dfox.me/2011/04/php-most-common-mistakes-part-2-using-post-increment-instead-of-pre-increment/ ):

for ( $i = calculateLoopLength (); $i ; — $i ) doSomething ( $i );
>
?>

In this case we could also replace the entire loop with a map, which might make your algorithm clearer (although this won’t work if calculateLoopLength() == 0):

array_map ( ‘doSomething’ ,
range ( 0 , calculateLoopLength () — 1 ));
?>

Источник

PHP for loops and counting arrays

It’s well known that calling count($array) in a for loop in PHP is slower than assigning the count to a variable and using that variable in the for loop instead. However until recently, I wasn’t aware that the assignment to a variable can be done in the for loop itself and share this here in this post.

The «wrong» way

The following example loops through an array in the variable $array:

The count() function is called on each loop which adds extra unecessary overhead. Even if the array only has a couple of items in it processing will still take longer than assigning count() to a variable.

The «right» way

Here’s one way of doing it the «right» way:

The count is now assigned to the variable $j so the function is only called once.

Another way of doing the above is like so:

The assignment $j = count($array) is part of the for loop, separated by a comma from the $i = 0 assignment. It is only called once at the start of the loop. It is not necesssarily superior to the first «right» example above but it does reduce the number of lines of code by one and means the purpose of the variable is clearly for of the loop.

Benchmarking

Out of interest I created an array with 100 elements and looped through the «wrong» way and the «right» way (and the whole thing 10,000 times for measurement purposes); the «right» way averaged about .20 seconds on my test box and the «wrong» way about .55 seconds.

Obviously these sorts of micro-optimizations aren’t really going to have much of an effect on your own website (that .20 vs .55 seconds was looping through the test 10k times, remember) but it is interesting to see the differences.

Источник

Оцените статью