Skip to main content

Foreach Loop in PHP

In PHP, foreach statement is used to iterate over a collection of data, like PHP arrays. As per the name of this construct, it will keep on continue with the loop to traverse given input array for each of its element, without any condition.
We have slightly touched about how this is working in PHP while seeing about PHP loops. In this article, let us see about foreach statement with more details.
Unlike other PHP loop statements, whiledo..while and for, this PHP loop statement foreach contains no counters, conditions and no need of increments or decrements, explicitly. Rather, it will iterate with each element and will be useful, where all the elements of the array to be traversed unconditionally.

foreach Usage in PHP Script

We can use foreach statement in a PHP program with two various syntaxes differed based on the iteration behavior for getting array elements in the following type of ways.
  • For getting only array values.
  • For getting both key and value component of each element.

Getting Array Values

foreach syntax for getting only values of a given input array is as shown below.
foreach($input_array as $value) {
...
}
By using this foreach syntax the value of each $input_array element will be stored into $value, for each iteration, and, the array pointer will be moved to point next element of $input_array, to be iterated subsequently. For example,
$input_array = array("apple","orange","grapes");
foreach($input_array as $value) {
$caps_value_array[] = ucfirst($value);
}
print "<b>Getting Array Values</b>";
print "<pre>";
print_r($caps_value_array);
print "</pre>";
In the above PHP example program, there is an input array to be used for the foreach statement follows. Inside foreach block, each value of the array element is applied for PHP case conversion function ucfirst(), and stored into a new array. And the output of this program with the array values is shown below.
Getting Array Values
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Grapes
)
Since we have iterated only the value of given $input_array, these values are displayed with default numeric array index.

Getting both key and value

In this method, we can iterate an array or object for getting the element as <key,value> pair, on each iteration. And, we can use these keys instead of default numeric indices, while displaying resultant array to the browser. The syntax and example program for this method of using PHP foreach is given below which is slightly differed from the previous method.
foreach($input_array as $key=>$value) {
...
}
By using above foreach syntax, the key and value of $input_array are stored into the PHP variables, $key, $value, respectively. For example,
$input_assoc_array = array("fruit1"=>"apple","fruit2"=>"orange","fruit3"=>"grapes");
foreach($input_assoc_array as $key=>$value) {
$caps_assoc_array[$key] = ucfirst($value);
}
print "<b>Getting Array Values</b>";
print "<pre>";
print_r($caps_assoc_array);
print "</pre>";
This kind of usage is mainly for iterating associative arrays in PHP. And the output of this program will be as follows.
Getting Array Values
Array
(
    [fruit1] => Apple
    [fruit2] => Orange
    [fruit3] => Grapes
)

Alternative PHP Syntax Replicating foreachFunctionality

Both of the above foreach functionalities can also be obtained by using PHP while statements are shown below.
while (list(, $value) = each($input_array)) {
...
}
and
while (list($key, $value) = each($input_array)) {
...
}
But, the only difference is that the PHP foreach is capable of resetting input array automatically, while start iterating over it. But, before using either of above alternative syntax, we need to call PHP reset() to reset array pointer to the initial position.

Caution:

  • foreach PHP construct only supports data with array or object data type. Passing neither of these data types will cause PHP warning error.
    Warning: Invalid argument supplied for foreach() in ... on line ...
  • PHP errors occurred during failure of foreach execution, will not be controlled by using @ operator.
  • We can iterate with an input array having more than one dimension. The length of the list given to store elements of two-dimensional input array should be identical with the length of the input array.

Comments

Popular posts from this blog

Create facebook messenger chatbot using PHP

Chatbots are the latest sensation in social media communication channels. These automated chat systems are especially build to receive vistiors on social media chats and provide basic information to the visitors about your business. This information could include event schedules, product information, latest deals, store offers and general information about the brand. Entrepreneurs and brand marketers employ chatbots to handle the bulk of chats queries. This way, a large number of queries could be easily handled with minimum costs. Chatbots help reduces the dependence on human customer service representatives (CSR). These chatbots vet out common queries so that the human CSR cold focus on queries that require processing of multiple information sources. Since chatbots steer all conversation toward a pre-set direction, it is easy and time-efficient to use these chatbots instead of human CSR. In this article, I will create a simple Facebook chatbot that could carry out an

Build chatbot with node js and react js

User Experience is given a lot of attention while building any application these days. More and more brands are leveraging chatbots to service their customers, market their brand, and even sell their products. There are a lot of awesome tools out there which helps in building an intelligent bot very easily like Google’s DialogFlow, Amazon Lex, etc, most of which implement their own Natural Language Processing (NLP) logic. However, in some cases, we don’t really need an intelligent bot. Whenever we have a small application having a limited set of options to choose from, it’s not really necessary to use NLP based tools like Google’s DialogFlow. You need to integrate with them (which is pretty easy though), and you need to make a network call to get the results. Instead, you would want to define your rules locally in those cases. Here we will build a simple chatbot using React Simple Chatbot library and add it to our pizza-builder app using which we can build ou

Now About PHP Info

Have you ever heard about phpinfo(). Yes, this function is used to know about configuration details of PHP installed in our machine. Such detailed information returned by this phpinfo() includes platform information, PHP and server environment, HTTP header information, PHP core details like version and directives status, License information and etc. phpinfo() function has an optional argument. If this function is called with no argument, then will display all information. We can check it by executing the following code. <? php phpinfo (); ?> We can also request specific details to be displayed to the browser by passing available constants to this function. Following list shows such available options. INFO_GENERAL – This will return information about the platform, compiler, architecture, API and etc. INFO_CREDITS – This option provides a hyperlink which shows details about authors, documentation, QA and infrastructure team. INFO_CONFIGURATION – Disp