Loop through and array php

Loop through and array php

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.

Читайте также:  Python 3 new features

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 )
);

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 );
>
?>

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 ));
?>

Источник

6 ways to loop through an array in php

Today, we will learn how to loop through an array in PHP using while ****loop, for loop, & various PHP Array functions.

PHP is one of the easiest language and traversing through an array in php is very easy. Infact, most popular way to access items in array in php is using loops : while, for & do..while

1. While loop

The while loop is very common loop among all languages and PHP is not different. In fact, while loop is one of the most popular method to iterate over PHP array.

while(expression) // Code to be executed >

It means that, while the given expression (or condition) is true, execute the code inside the curly brackets, and check the expression again. Keep doing it, until expression becomes false.

How to Iterate over PHP array using while loop

The PHP arrays have elements which can be accessed via its index position, right?

So, we can use the while loop to change the index position incrementally or decrementally therefore accessing every element (or selective elements as per the condition).

Here, we will create an index position variable and start with 0th position which is first in an array.

The condition will be to continue fetching element from an array til our index values is less than the count of array (or length of the given array).

Since, while loop will not increment our index variable automatically, we need to increment it inside the loop. Therefore, with each iteration, variable will move to next index position.

 $users = ['john', 'dave', 'tim']; $i = 0; while($i  count($users))  echo $users[$i]."\n"; $i++; > ?>

2. do while Loop

Well, personally it’s my least favorite loop in every programming language, so I’d probably say less.

The do while is another type of loop in php (and mostly all programming languages . except some functional languages .. Yes, I am looking at you Smalltalk )

It is mostly similar to while loop, except the ordering is reverse.

  • In while loop, condition or expression is checked first & if true, then the code inside the loop gets executed
  • In do while loop, code inside the loop gets executed first & then the condition is checked. If condition is true, then it will execute the code again and so on.
do  // Code to be executed > while(expression);

It means that, while the given expression (or condition) is true, execute the code inside the curly brackets, and check the expression again. Keep doing it, until expression becomes false.

Note: Don’t miss the semicolon at the end. I always forget that.

Without further ado, let’s recrete previous example using do while loop

How to loop through php array using do while loop

We will iterate over an array of users using do while loop.

 $users = ['john', 'dave', 'tim']; $i = 0; do  echo $users[$i]."\n"; $i++; > while($i  count($users)); ?>

3. For Loop

Let’s talk about the MOST popular loop. The for loop.

The for loop is my most favorite general loop (next one I use often for this particular usecase) for any general iterative usecase. It does the exactly same as while loop but it has different, more compact syntax.

for (expr1; expr2; expr3)  //Code to be executed > 

It looks very complex at first, but when you get bit experience, believe me, you will prefer this most of the time.

It has placeholder for three expressions (each are optional, so you can still use this loop just like while)

  • Expr1 — It gets executed once at the beginning of the loop, so normally it is used to initialize any counters to be used.
  • Expr2 — This is the condition part. At the beginning of each iteration, this expression gets evaluated and if true then only it will continue.
  • Expr3 — It gets execute at the end of the iteration. Normally used to increment/decrement our counters.

Let’s recreate our example using for loop.

How to loop through array using for loop in PHP

As shown below, it is exactly same as while loop, except it’s condensed and better syntax. Also, for one line statements, you can omit curly brackets 😉

 $users = ['john', 'dave', 'tim']; for($i = 0;$i  count($users);$i++) echo $users[$i]."\n"; ?> 

4. Foreach Loop

Talking about condensed syntax, let’s talk about another great and special loop — Foreach loop.

This loop is only helpful when you want to iterate over each item. If for example — you want to access only even position items, then sadly this loop is not for you, you need to use above loops.

But, for the particular use of accessing each item (see the pun?), foreach is my favorite and infact would be everyone’s favorite. It is very simply and easy to use.

//without key foreach (iterable_expression as $value) statement //with key foreach (iterable_expression as $key => $value) statement

Let’s checkout the example:

How to loop over array using foreach loop in PHP

Let’s recreate our example. We won’t need the keys (position) therefore we will use foreach without keys.

 $users = ['john', 'dave', 'tim']; foreach($users as $user) echo $user."\n"; ?>

5. array_walk

The array_walk is an array function provided by PHP which applies the given function to each element in the array, hence the name «array_walk».

array_walk(array|object &$array, callable $callback, mixed $arg = null): bool
  • array — It is the input array to iterate over.
  • callback — It is a function passed to this function which will act on each item one by one. This function takes two parameters — 1. Item value 2. Index position of the item
  • args — It is the optional arguments which if supplied, will be passed as third parameter to callback function.

It returns true when executed successfully.

Let’s recreate our example:

 $users = ['john', 'dave', 'tim']; function print_item($item, $key)  echo $item."\n"; > array_walk($users, 'print_item'); ?>

6. Array Iterator

This is quite advanced and complex way to iterate over an array. Honestly, I don’t see the reason why you would need to use this over other methods, but for the purpose of fun & learning, let’s explore this.

Here, we will create ArrayIterator object using ArrayObject function and use it to iterate over an array. It is based on pointer mechanism just like C++.

 $users = ['john', 'dave', 'tim']; $array_object = new ArrayObject($users); $array_iterator = $array_object->getIterator(); while( $array_iterator->valid() )  echo $array_iterator->current() . "\n"; $array_iterator->next(); > ?>

Conclusion

We saw 6 ways to loop over an array in PHP so far. Personally, I like to use foreach because it is very simple but you can use any of the above method. Hope, this helped.

Источник

PHP foreach Loop

The foreach loop — Loops through a block of code for each element in an array.

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Examples

The following example will output the values of the given array ($colors):

Example

foreach ($colors as $value) echo «$value
«;
>
?>

The following example will output both the keys and the values of the given array ($age):

Example

You will learn more about arrays in the PHP Arrays chapter.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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