From the two examples below, for and foreach have the capability to produce the same results for looping condition. I then search in other discussion about the benchmark and found that there is not much difference in performance between the two functions.
Thus, I want to know for web developers on how these two functions differ in handling programs.
When to use for? When to use foreach? Please provide me with some examples.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
<html>
<body>
<?php
for( $i = 0; $i<5; $i++ ) {
echo("Value of i is $i <br />" );
}
?>
</body>
</html>
When we use for loop we need a condition after satisfying which the
loop will continue. For this reason we use some counters in our loop
which obviously occupies some memory.
But while using foreach loop we don't have to think about the
counter. In case of foreach loop there is no extra memory required
for the counters also. Because we don't have any counter in foreach
loop.
Both the techniques have advantages and disadvantages, the foreach
loop is used mainly in arrays and collections but for statement can
be used in any program.
foreach is specifically for iterating over elements of an array or object.
for is for doing something... anything... that has a defined start condition, stop condition, and iteration instructions.
So, for can be used for a much broader range of things. In fact, without the third expression - without the iteration instructions - a for becomes a while.
For each is used for iterating through arrays or object that use keys and values.
For example, if I had an array called 'User':
$User = array(
'name' => 'dinesh',
'email' => 'dinesh#xyz.com',
'age' => 25
);
I could iterate through that very easily and still make use of the keys:
foreach ($User as $key => $value) {
echo $key.' is '.$value.'<br />';
}
This would print out:
name is dinesh
email is dinesh#xyz.com
age is 25
With for loops, it's more difficult to retain the use of the keys.
When you're using object-oriented practice in PHP, you'll find that you'll be using foreach almost entirely, with for loops only for numerical or list-based things. foreach also prevents you from having to use count($array) to find the total number of elements in the array.
Related
Editing this question entirely, for future learners.
I initially asked if a single while function could replace the code below. I didn't realize while doesn't increment automatically like foreach, so no. Great answers below on better solutions using either array_slice() or the classic for loop.
foreach ($array as $key => $value) {
if ($key < 25) {
echo '<img src="'.$value.'/preview_image.jpg">';
}
}
You would still have to increment the key, plus the key would have to be uniform to work.
Foreach works on the set and is more resilient against gaps in the range. Iterating over a set with for example 1,2 and 4 as keys, works great with foreach.
Another method could be:
for ($i=0;$i<25;$i++) etc
This checks the end conditions straight away, but does not take gaps into account, which could lead to extra code in the for loop itself.
You can use simple for loop
like this
for($i = 0; $i < 25; $i++)
{
echo '<img src="'.$array[$i].'/preview_image.jpg">';
}
I like array_slice() solution.
Also you should use Alternative syntax for control structures for displaying HTML.
PHP: Alternative syntax for control structures - Manual
<?php
/* Logic Part */
$array = [...];
$array = array_slice($array, 0, 25);
// You MUST apply this function before echoing user inputs
// for the sake of security reasons.
function h($s)
{
return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
/* HTML Part */
?>
<!DOCTYPE html>
<meta charset="UTF-8">
<title>Example</title>
<div>
<?php foreach ($array as $value): ?>
<img src="<?=h($value)?>/preview_image.jpg">
<?php endforeach; ?>
</div>
You effectively want to retrieve the first 24 lines from a file.
There are many ways to do that.
This is one way:
$file = new SplFileObject($path);
$file->setFlags($file::DROP_NEW_LINE);
$head = new LimitIterator($file, 0, 24);
foreach ($head as $value) {
...
}
The benefit is that you get a plain variable to foreach over that provides the data you need. This works with the Decortator pattern and is pretty flexible.
If the file has less than 24 lines (records), the foreach will finish earlier.
Also this code would not read the whole file into memory only to provide the first 24 lines.
I have this object containing one row and many keys/variables with numbered names.
I need to pass each of them one at a time to another function. How do I loop through the keys instead of the rows?
The code would look like this:
foreach ($object['id'] as $row):
$i++;
$data['myInfo'][$i] = $this->get_data->getInfo('data1', 'id', $row->{'info'.$i.'_id'});`
but this obviously won't work since it's looping through the rows/instances of an object, and I have only one row in my $object['id'] object (with info1_id, info2_id, info3_id, info4_id... etc keys), so the loop stops after just one cycle. And I really don't feel like typing all of that extra code by hand, there's gotta be solution for this. :)
You can just iterate through your object like an array :
foreach ($object['id'] as $row) {
foreach ($row as $k => $v) {
$id = substr($k, 4, strpos($k, '_')-4);
$data['myInfo'][$id] = $this->get_data->getInfo('data1', 'id', $v);`
}
}
Thanks for the directions Alfwed, I didn't know you could use foreach loop for anything other than instances of an object or arrays (only started learning php a week or so ago), but now it looks pretty straight forward. that's how I did it:
foreach ($object['id'] as $row):
foreach ($row as $k=>$v):
$i++;
if ($k == print_r ('info'.$i.'_id',true)){
$data['myinfo'][$i] = $this->get_db->getRow('products', 'id','info'.$i.'_id');
<...>
in my case, I knew how many and where were those values, so I didn't have to worry about index values too much.
Let's say I'm trying to combine items from two lists, and I want to get this result:
A7
A8
B7
B8
This is my code:
<?php
$list1_array = array('A', 'B');
$list2_array = array('7', '8');
while(list( , $item1) = each($list1_array)) {
while(list( , $item2) = each($list2_array)) {
echo $item1.$item2."<br />";
}
}
?>
I get this result:
A7
A8
I seems like outside 'while' doesn't make the second loop?
What am I doing wrong?
While it might be better to use a slightly more common (perhaps more readable) approach (e.g. by using foreach loops as shown by GolezTrol,) in answer to your original questions:
The problem is most likely happening because the internal "cursor" (or "pointer") for your array is not being reset... so it never gets back to the start of the original array.
Instead, what if you try something like this:
<?php
$list1_array = array('A', 'B');
$list2_array = array('7', '8');
while(list(,$item1) = each($list1_array)) {
while(list(,$item2) = each($list2_array)) {
echo $item1.$item2."<br />";
}
reset($list2_array);
}
?>
Why not use foreach?
foreach ($list1_array as $item1)
{
foreach ($list2_array as $item2)
{
echo $item1.$item2."<br />";
}
}
Using a while loop with each makes the loop depend on the array pointer. An array has a pointer that tells you which item is the 'current' one. You can use functions like current to get the current item in the array. each is also such a function. It returns the current item (or actually an array with the key and value of the current item).
And therein lies the problem. The inner while loop stops when you are at the end of the array. So for the first item of the outer array (array1), the inner while loop (array2) runs fine. But the second time, the pointer is still at the end of the array and each returns false right away.
So, the solution could be to reset the array pointer, using the reset function as sharply pointed out by #summea. Or you can use a foreach loop, which is not affected by this fenomenon, because it resets the array pointer itself when it starts. Also, I this it's more readable, especially due to the weird list construct. Nevertheless, it might be good to know how the internals work, and your while loop works more low-level than foreach.
If I have a foreach construct, like this one:
foreach ($items as $item) {
echo $item . "<br />";
}
I know I can keep track of how many times the construct loops by using a counter variable, like this:
$counter = 0;
$foreach ($items as $item) {
echo $item.' is item #'.$counter. "<br />";
$counter++;
}
But is it possible to do the above without using a "counter" variable?
That is, is it possible to know the iteration count within the foreach loop, without needing a "counter" variable?
Note: I'm totally okay with using counters in my loops, but I'm just curious to see if there is a provision for this built directly into PHP... It's like the awesome foreach construct that simplified certain operations which are clunkier when doing the same thing using a for construct.
No it's not possible unless your $items is an array having contiguous indexes (keys) starting with the 0 key.
If it have contiguous indexes do:
foreach ($items as $k => $v)
{
echo $k, ' = ', $v, '<br />', PHP_EOL;
}
But as others have stated, there is nothing wrong using a counter variable.
There's no easier way - that's kinda what count variables are for.
I'm assuming that you want to know the current count during the loop. If you just need to know it after, use count($items) as others have suggested.
You could tell how many time it WILL loop or SHOULD have looped by doing a
$loops = count($items);
However that will only work if your code does not skip an iteration in any way.
foreach loops N times, where N is just the size of the array. So you can use count($items) to know it.
EDIT
Of course, as noticed by Bulk, your loop should not break (or maybe continue, but I would count a continue as a loop, though shorter...)
Recently I experienced this weird problem:
while(list($key, $value) = each($array))
was not listing all array values, where replacing it with...
foreach($array as $key => $value)
...worked perfectly.
And, I'm curious now.. what is the difference between those two?
Had you previously traversed the array? each() remembers its position in the array, so if you don't reset() it you can miss items.
reset($array);
while(list($key, $value) = each($array))
For what it's worth this method of array traversal is ancient and has been superseded by the more idiomatic foreach. I wouldn't use it unless you specifically want to take advantage of its one-item-at-a-time nature.
array each ( array &$array )
Return the current key and value pair from an array and advance the array cursor.
After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.
(Source: PHP Manual)
Well, one difference is that each() will only work on arrays (well only work right). foreach will work on any object that implements the traversable interface (Which of course includes the built in array type).
There may be a micro-optimization in the foreach. Basically, foreach is equivilant to the following:
$array->rewind();
while ($array->valid()) {
$key = $array->key();
$value = $array->current();
// Do your code here
$array->next();
}
Whereas each basically does the following:
$return = $array->valid() ? array($array->key(), $array->current()) : false;
$array->next();
return $return;
So three lines are the same for both. They are both very similar. There may be some micro-optimizations in that each doesn't need to worry about the traversable interface... But that's going to be minor at best. But it's also going to be offset by doing the boolean cast and check in php code vs foreach's compiled C... Not to mention that in your while/each code, you're calling two language constructs and one function, whereas with foreach it's a single language construct...
Not to mention that foreach is MUCH more readable IMHO... So easier to read, and more flexible means that -to me- foreach is the clear winner. (that's not to say that each doesn't have its uses, but personally I've never needed it)...
Warning! Foreach creates a copy of the array so you cannot modify it while foreach is iterating over it. each() still has a purpose and can be very useful if you are doing live edits to an array while looping over it's elements and indexes.
// Foreach creates a copy
$array = [
"foo" => ['bar', 'baz'],
"bar" => ['foo'],
"baz" => ['bar'],
"batz" => ['end']
];
// while(list($i, $value) = each($array)) { // Try this next
foreach($array as $i => $value) {
print $i . "\n";
foreach($value as $index) {
unset($array[$index]);
}
}
print_r($array); // array('baz' => ['end'])
Both foreach and while will finish their loops and the array "$array" will be changed. However, the foreach loop didn't change while it was looping - so it still iterated over every element even though we had deleted them.
Update: This answer is not a mistake.
I thought this answer was pretty straight forward but it appears the majority of users here aren't able to appreciate the specific details I mention here.
Developers that have built applications using libdom (like removing elements) or other intensive map/list/dict filtering can attest to the importance of what I said here.
If you do not understand this answer it will bite you some day.
If you passed each an object to iterate over, the PHP manual warns that it may have unexpected results.
What exactly is in $array