Robert Sinclair Robert Sinclair - 2 months ago 20
PHP Question

Add array item then re-evaluate new array

Have been scratching my head for a few hours on this, seems like a silly issue, but just can't find a solution.

Here's my sample code:

$continueLoop = true;
$colorsArray = array("red", "white", "blue");

while($continueLoop == true) {

$arrayCount = count($colorsArray);

for ($i=0; $i < $arrayCount; $i++) {
echo "evaluating ".$colorsArray[$i]."<br>";
if($colorsArray[$i] == "blue") {
array_push($colorsArray, "YELLOW");
break;
}
}

if(count($colorsArray) == 4) {
$continueLoop = false;
}

}


It outputs


red

white

blue


Basically I am adding a color "YELLOW" and then it should walk through the whole array again. But it's ignoring the newly added array item.

I know it does recognize the item, because the while loop will keep running until $colorsArray has 4 items (in the beginning it has only 3).

So why is it not Echo'ing "YELLOW"?

I've tried a few different solutions, just pushing the item using $array[], using foreach, array_values etc. etc.

Thank you

Update:

If i put


if(count($colorsArray) == 10) {


Still still won't print Yellow

Answer

Will probably clean this up in a moment but just quickly this should do the job;

$colorsArray = array("red", "white", "blue");

for ($i=0; $i < count($colorsArray); $i++) {
    echo "evaluating ".$colorsArray[$i]."<br>";
    if($colorsArray[$i] == "blue" && !in_array('YELLOW', $colorsArray)) {
        array_push($colorsArray, "YELLOW");
    }
}

print_r($colorsArray);

Essentially you use count on each iteration, since the length of the array changes, it now has another element to loop through.

Edit: If you want it to walk through the whole array again, just set $i = -1; after you push in a new element.

Edit2: A little clean up.

$colours = array('red', 'white', 'blue');

for ($i = 0; $i < count($colours); ++$i) {
    echo 'Evaluating: ' . $colours[$i] . '<br/>';

    if ($colours[$i] === 'blue' && !in_array('Yellow', $colours)) {
        array_push($colours, 'Yellow');
        $i = -1;
    }
}

Output:

Evaluating: red
Evaluating: white
Evaluating: blue
Evaluating: red
Evaluating: white
Evaluating: blue
Evaluating: Yellow
  • If you reset the loot to 0 rather than -1 then you skip the first loop iteration, i.e. you miss out red.
  • Not sure on your dataset / purpose for this but I imagine you would want 'Yellow' to be dynamic.