InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Iterating Through an Array in PHP
PHP

Iterating Through an Array in PHP

InfinityCoder November 19, 2016

You want to cycle though an array and operate on all or some of the elements inside.

Use foreach:

1
2
3
foreach ($array as $value) {
    // Act on $value
}

Or to get an array’s keys and values:

1
2
3
foreach ($array as $key => $value) {
    // Act II
}

Another technique is to use for:

1
2
3
for ($key = 0, $size = count($array); $key < $size; $key++) {
   // Act III
}

Finally, you can use each() in combination with list() and while:

1
2
3
4
reset($array); // reset internal pointer to beginning of array
while (list($key, $value) = each ($array)) {
    // Final Act
}

A foreach loop is the most concise way to iterate through an array:

1
2
3
4
5
6
7
8
9
// foreach with values
foreach ($items as $cost) {
    // ...
}
 
// foreach with keys and values
foreach($items as $item => $cost) {
    // ...
}

With foreach, PHP iterates over a copy of the array instead of the actual array. In contrast, when using each() and for, PHP iterates over the original array.

So if you modify the array inside the loop, you may (or may not) get the behavior you expect.
If you want to modify the array, reference it directly:

1
2
3
4
5
foreach ($items as $item => $cost) {
    if (! in_stock($item)) {
        unset($items[$item]);         // address the array directly
    }
}

The variables returned by foreach() aren’t aliases for the original values in the array: they’re copies, so if you modify them, it’s not reflected in the array.

That’s why you need to modify $items[$item] instead of $cost.

When using each(), PHP keeps track of where you are inside the loop.

After completing a first pass through, to begin again at the start, call reset() to move the pointer back to the front of the array.

Otherwise, each() returns false. The for loop works only for arrays with consecutive integer keys.

Unless you’re modifying the size of your array, it’s inefficient to recompute the count() of $items each time through the loop, so we always use a $size variable to hold the array’s size:

1
2
3
for ($item = 0, $size = count($items); $item < $size; $item++) {
    // ...
}

If you prefer to count efficiently with one variable, count backward

1
2
3
for ($item = count($items) - 1; $item >= 0; $item--) {
    // ...
}

The associative array version of the for loop is:

1
2
3
for (reset($array); $key = key($array); next($array) ) {
   // ...
}

This fails if any element holds a string that evaluates to false, so a perfectly normal value such as 0 causes the loop to end early. Therefore, this syntax is rarely used, and is included only to help you understand older PHP code.
Finally, use array_map() to hand off each element to a function for processing:

1
2
// lowercase all words
$lc = array_map('strtolower', $words);

The first argument to array_map() is a function to modify an individual element, and the second is the array to be iterated through.
Generally, we find this function less flexible than the previous methods, but it is wellsuited for the processing and merging of multiple arrays.
If you’re unsure if the data you’ll be processing is a scalar or an array, you need to protectagainst calling foreach with a nonarray. One method is to use is_array():

1
2
3
4
5
if (is_array($items)) {
   // foreach loop code for array
} else {
   // code for scalar
}

Another method is to coerce all variables into array form using settype(): 

1
2
settype($items, 'array');
// loop code for arrays

This turns a scalar value into a one-element array and cleans up your code at the expense of a little overhead.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Counting Lines, Paragraphs, or Records in a File in PHP
You want to count the number of lines, paragraphs, or …

Counting Lines, Paragraphs, or Records in a File in PHP

Setting XSLT Parameters from PHP in PHP
You want to set parameters in your XSLT stylesheet from …

Setting XSLT Parameters from PHP in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap