Converting a Foreach to a for loop - php

I have a 3rd party script that loops through every returned value and echos it.
I want to limit the amount to 3 loops but am having issues.
current loop:
foreach($json->data as $v)
{
echo $v->from->name."<br>";
}
I want to do something like:
for ($i=0;$i<3;$i++)
{
echo $v->from->name."<br>";
}
Is there any work around without having to rework the whole script.

If $json is a integer-indexed array (although I doubt it)
for ($i=0;$i<3;$i++)
{
echo $json->data->from->name."<br>";
}
otherwise a less elegant solution would be
$i = 0;
foreach($json->data as $v)
{
echo $v->from->name."<br>";
if(++$i == 3) {break;}
}
finally
foreach(slice($json->data, 0, 3, TRUE) as $v)
{
echo $v->from->name."<br>";
}

No need to convert it in to for loop put an extra counter like this.
$count=0;
foreach($json->data as $v)
{
if ($count == 3)
{
break;
}
echo $v->from->name."<br>";
$count++;
}

Slice the first 3 elements off the array and loop over those.

Related

How to check if a array is even or odd php

I have an array and I need to find if the values are even or odd and print them.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
And I print the results in array format (I`m looking to use "echo" to print each)
I found a solution that is to create a while loop and use modules %2
like:
$foreach ($numbers % 2==0) { //even
echo "value is even";
} else {
echo "value is odd";
}
But it doesnt work, and i only have experience working with numbers in if statements and loops. How would i go about this when working with an array.
Thanks in advance.
Welcome to Stackoverflow.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
foreach ($numbers as $n) {
echo 'value '. $n .' is: ';
echo ($n % 2 == 0) ? 'even' : 'odd';
echo "\n"; // optional
}
You can try also like this, this is more understandable for you
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
foreach($numbers as $value)
{
if($value%2==0)
{
echo $value 'is even <br/>';
}
else
{
echo $value 'is odd <br/>';
}
}
Here is the code,
You are in right direction but there will be a little bit of change in your code i.e. you are applying condition on whole array which is wrong you have to fetch single value and apply even number condition.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
foreach($numbers as $var)
{
if($var%2==0)
{
echo $var;
}
else
{
echo $var;
}
}

How can I repeat a specific iteration in a foreach loop in PHP?

As there is no iterator in PHP, the only way to loop through an array without getting the length of the array is to use foreach loop.
Let say I have the following loop:
foreach ($testing_array as $testing_entry) {
$result = my_testing_api_call($testing_entry);
if ($result == 'server dead')
break;
else if ($result == 'done') {
// do something to handle success code
continue;
}
else {
sleep(5);
// I want to retry my_testing_api_call with current $testing entry, but don't know what to write
}
}
One way to do that is to use for loop instead.
for ( $i=0; $i < count($testing_array); $i++ ) {
$result = my_testing_api_call($testing_entry[$i]);
if ($result == 'server dead')
break;
else if ($result == 'done') {
// do something to handle success code
continue;
}
else {
sleep(5);
$i--; //so it will repeat the current iteration.
}
}
The problem is that the $testing_array is not originally using number as index, so I have to do some data massage to use a for loop. Is there a way I can repeat a specific iteration in a foreach loop?
Perhaps a do-while will work for you.
Untested Code:
foreach ($testing_array as $testing_entry) {
do {
$result = my_testing_api_call($testing_entry);
if ($result == 'server dead') {
break 2; // break both loops
} elseif ($result == 'done') {
// do something to handle success code
} else {
sleep(5);
// I want to retry my_testing_api_call with current $testing entry, but don't know what to write
}
} while ($result !== 'done');
}
Or a single loop structure that destroys the input array as it iterates.
Untested Code:
$result = '';
while ($testing_array && $result !== 'server dead') {
$result = my_testing_api_call(current($testing_array));
if ($result == 'done') {
// do something to handle success code
array_shift($testing_array);
} elseif ($result !== 'server dead') {
sleep(5); // I want to retry my_testing_api_call with current $testing entry, but don't know what to write
}
}
Or you can use your for loop by indexing $test_array with array_values() if you don't need the keys in your // do something.
$testing_array = array_values($testing_array);
for ($i=0, $count=count($testing_array); $i < $count; ++$i) {
$result = my_testing_api_call($testing_entry[$i]);
if ($result == 'server dead') {
break;
} else if ($result == 'done') {
// do something to handle success code
} else {
sleep(5);
--$i; //so it will repeat the current iteration.
}
}
If you do need the keys down script, but you want to use for, you could store an indexed array of keys which would allow you to use $i to access the keys and maintain data synchronicity.
My final suggestion:
Use while (key($testing_array) !== null) {...} to move the pointer without destroying elements.
Code: (Demo)
$array1 = [
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
];
while (key($array1)!==null) { // check if the internal pointer points beyond the end of the elements list or the array is empty
$current = current($array1);
$key = key($array1);
echo "$key => $current\n"; // display current key value pair
if ($current < 3) { // an arbitrary condition
echo "\t";
$array1[$key] = ++$current; // increment the current value
} else { // current value is satisfactory
echo "\t(advance pointer)\n";
next($array1); // move pointer
}
}
Output:
one => 1
one => 2
one => 3
(advance pointer)
two => 2
two => 3
(advance pointer)
three => 3
(advance pointer)
four => 4
(advance pointer)
You are trying to handle two different things in your loop, that makes it hard to write clean control flow. You could separate the retry-logic from the result handling:
function call_api_with_retry($entry) {
do {
if (is_defined($result)) sleep(5);
$result = my_testing_api_call($entry);
} while ($result != 'done' && $result != 'server dead');
return $result;
}
foreach ($testing_array as $testing_entry) {
$result = call_api_with_retry($testing_entry);
if ($result == 'server dead')
break;
else if ($result == 'done') {
// do something to handle success code
continue;
}
}
(there might be syntax errors, it's been a while since I wrote PHP code)
To repeat a single specific iteration you need to add a control mechanism, it is not an intended behavior after all.
There are many suggestions here, all of them are kinda over-engineered.
PHP is a high level derivate of C and both languages have the 'goto' operator, it has a bad reputation because people have historically used it too much.
In the end a foreach/while loop is internally nothing else than a 'goto' operation.
Here is the code:
foreach ($array as $key => $value)
{
restart:
if ($value === 12345) goto restart;
}
That's how this should be done just keep in mind that this can cause an endless loop, like in the example.
Look at the next complicated version without goto:
foreach ($array as $key => $value) while(1)
{
if ($value === 12345) continue;
break;
}
This is essentially the same as the goto, just with more code.
If you'd want to "break" or "continue" the foreach loop you'd write "break 2" or "continue 2"

break out of if and foreach

I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.
foreach ($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ($current_device[0] == $device) {
// Found a match in the file.
$nodeid = $equip->id;
<break out of if and foreach here>
}
}
if is not a loop structure, so you cannot "break out of it".
You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop immediately and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
Just for completeness for others who stumble upon this question looking for an answer..
break takes an optional argument, which defines how many loop structures it should break. Example:
foreach (['1','2','3'] as $a) {
echo "$a ";
foreach (['3','2','1'] as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
Resulting output:
1 3 2 1 !
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break. That will do it.
A safer way to approach breaking a foreach or while loop in PHP is to nest an incrementing counter variable and if conditional inside of the original loop. This gives you tighter control than break; which can cause havoc elsewhere on a complicated page.
Example:
// Setup a counter
$ImageCounter = 0;
// Increment through repeater fields
while ( condition ):
$ImageCounter++;
// Only print the first while instance
if ($ImageCounter == 1) {
echo 'It worked just once';
}
// Close while statement
endwhile;
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here

Can't change a value inside a php list

I have the following php loop that takes an array that contains a set of arrays. I use this code to convert each array to a list, so I can manipulate the elements better.
This is my code...
while ($i<sizeof($my_array)){
while(list($key,$val) = each($my_array[$i])){
$j = $i+1;
if ($key == "fruit"){
$val = "ananas".$j;
echo $val;
}
}
$i++;
}
When I print the "search" array (print_r($my_array)), the values don't change. I don't understand why this doesn't work as I had expected. Is there a solution to modify the $val without changing the loop structure and logic?
Use foreach with reference:
$i = 0;
foreach ( $my_array as $key => &$val ) {
++$i;
if ($key == "fruit"){
$val = "ananas" . $i;
echo $val;
}
}
$val is a copy of the data contained in $my_array[$i], not the actual data. To change the data in the array:
while ($i<sizeof($my_array)){
while(list($key,$val) = each($my_array[$i])){
$j = $i+1;
if ($key == "fruit"){
$my_array[$i][$key] = "ananas";
echo $my_array[$i][$key];
}
}
$i++;
}
And it's probably easier to use a foreach loop
each() doesn't pass the data as references, without modifying the loop that much:
if ($key == "fruit"){
$val = "ananas";
echo $val;
$my_array[$i][$key] = $val;
}
Of course, there are better ways to do that. But you wanted an answer that didn't change the loop structure.

How to skip the 1st key in an array loop?

I have the following code:
if ($_POST['submit'] == "Next") {
foreach($_POST['info'] as $key => $value) {
echo $value;
}
}
How do I get the foreach function to start from the 2nd key in the array?
For reasonably small arrays, use array_slice to create a second one:
foreach(array_slice($_POST['info'],1) as $key=>$value)
{
echo $value;
}
foreach(array_slice($_POST['info'], 1) as $key=>$value) {
echo $value;
}
Alternatively if you don't want to copy the array you could just do:
$isFirst = true;
foreach($_POST['info'] as $key=>$value) {
if ($isFirst) {
$isFirst = false;
continue;
}
echo $value;
}
Couldn't you just unset the array...
So if I had an array where I didn't want the first instance,
I could just:
unset($array[0]);
and that would remove the instance from the array.
If you were working with a normal array, I'd say to use something like
foreach (array_slice($ome_array, 1) as $k => $v {...
but, since you're looking at a user request, you don't have any real guarantees on the order in which the arguments might be returned - some browser/proxy might change its behavior or you might simply decide to modify your form in the future. Either way, it's in your best interest to ignore the ordering of the array and treat POST values as an unordered hash map, leaving you with two options :
copy the array and unset the key you want to ignore
loop through the whole array and continue when seeing the key you wish to ignore
in loop:
if ($key == 0) //or whatever
continue;
Alternative way is to use array pointers:
reset($_POST['info']); //set pointer to zero
while ($value=next($_POST['info']) //ponter+1, return value
{
echo key($_POST['info']).":".$value."\n";
}
If you're willing to throw the first element away, you can use array_shift(). However, this is slow on a huge array. A faster operation would be
reset($a);
unset(key($a));
On a array filled with 1000 elements the difference is quite minimal.
Test:
<?php
function slice($a)
{
foreach(array_slice($a, 1) as $key)
{
}
return true;
}
function skip($a)
{
$first = false;
foreach($a as $key)
{
if($first)
{
$first = false;
continue;
}
}
return true;
}
$array = array_fill(0, 1000, 'test');
$t1 = time() + microtime(true);
for ($i = 0; $i < 1000; $i++)
{
slice($array);
}
var_dump((time() + microtime(true)) - $t1);
echo '<hr />';
$t2 = time() + microtime(true);
for ($i = 0; $i < 1000; $i++)
{
skip($array);
}
var_dump((time() + microtime(true)) - $t2);
?>
Output:
float(0.23605012893677)
float(0.24102783203125)
Working Code From My Website For Skipping The First Result and Then Continue.
<?php
$counter = 0;
foreach ($categoriest as $category) { if ($counter++ == 0) continue; ?>
It is working on opencart also in tpl file do like this in case you need.
foreach($_POST['info'] as $key=>$value) {
if ($key == 0) { //or what ever the first key you're using is
continue;
} else {
echo $value;
}
}
if you structure your form differently
<input type='text' name='quiz[first]' value=""/>
<input type='text' name='quiz[second]' value=""/>
...then in your PHP
if( isset($_POST['quiz']) AND
is_array($_POST['quiz'])) {
//...and we'll skip $_POST['quiz']['first']
foreach($_POST['quiz'] as $key => $val){
if($key == "first") continue;
print $val;
}
}
...you can now just loop over that particular structure and access rest normally
How about something like this? Read off the first key and value using key() and current(), then array_shift() to dequeue the front element from the array (EDIT: Don't use array_shift(), it renumbers any numerical indices in the array, which you don't always want!).
<?php
$arr = array(
'one' => "ONE!!",
'two' => "TWO!!",
'three' => "TREE",
4 => "Fourth element",
99 => "We skipped a few here.."
) ;
$firstKey = key( $arr ) ;
$firstVal = current( $arr ) ;
echo( "OK, first values are $firstKey, $firstVal" ) ;
####array_shift( $arr ) ; #'dequeue' front element # BAD! renumbers!
unset( $arr[ $firstKey ] ) ; # BETTER!
echo( "Now for the rest of them" ) ;
foreach( $arr as $key=>$val )
{
echo( "$key => $val" ) ;
}
?>

Categories