Blog Details

foreach loop


                                
                                    <h2></h2>
<h2><strong>foreach loop</strong></h2>
<ul>
	<li><span style="font-size: 13px;">The </span><em style="font-size: 13px;">foreach</em><span style="font-size: 13px;"> construct provides an easy way to iterate over arrays.</span></li>
	<li><span style="font-size: 13px;"> </span><em style="font-size: 13px;">foreach</em><span style="font-size: 13px;"> works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. </span></li>
	<li><span style="font-size: 13px;">There are<strong> two syntaxes:</strong></span></li>
</ul>
&nbsp;
<h2>Syntax :</h2>
<ul>
	<li><span style="font-size: 1.5em;">f</span><strong style="font-size: 1.5em;">oreach (array_expression as $value) statement</strong></li>
	<li>
<h2>foreach (array_expression as $key =&gt; $value) statement</h2>
</li>
</ul>
&nbsp;
<ul>
	<li><span style="font-size: 13px;">The <strong>first form</strong> loops over the array given by </span><strong><em style="font-size: 13px;">array_expression</em></strong><span style="font-size: 13px;">. On each iteration, the value of the <strong>current element is assigned</strong> to </span><strong><em style="font-size: 13px;">$value</em></strong><span style="font-size: 13px;"> and the <strong>internal array</strong> pointer is advanced <strong>by one</strong> (so on the next iteration, you'll be looking at the next element).</span></li>
</ul>
<ul>
	<li>The <strong>second form</strong> will additionally<strong> assign</strong> the current <strong>element's key</strong> to the <em>$key</em> variable on each iteration.</li>
</ul>
&nbsp;
<h2><strong>Example 1:</strong></h2>
&lt;?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &amp;$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?&gt;

&nbsp;
<h2><strong>Example 2:</strong></h2>
&lt;?php
foreach (array(1, 2, 3, 4) as &amp;$value) {
$value = $value * 2;
}
?&gt;
<h2></h2>
&nbsp;
<h2><strong> </strong></h2>
<pre><strong> </strong></pre>
                                    


Categories

Core_PHP

Latest posts

13.05.14
Implementing CRUD Operations ¶

<ul> <li>Now comes the fun part. We would like t

13.05.14
View

<ol> <li><a href="http://www.yiiframework.com/do

13.05.14
Creating Model

<ol> <li><a href="http://www.yiiframework.com/do

Get Free Quote