Alexxosipov
Alexxosipov

Reputation: 1244

Why php doesn't exit from loop via break?

I have the for loop:

I have an $request->photos array. Keys from this array are:

[1,3,5,8]

In the end, I need to get an array, where indexes are from 1 to 8 and items are boolean variables. Aside from this, I need to save the photos from the array.

Then I need to loop through the array and check if $i equals to $key:

foreach($request->photos as $key => $photo) {
    for($i = 1; $i < 9; $i++) {
        if ($key == $i) {
            dump($key);
            $path = storage_path('app/public/images/' . $pdf->id . '-' . $key . '.png');
            $image = Image::make($photo->getRealPath())->widen(300)->save($path);
            $imagesArray[$i] = true;
            break;
        } else {
            $imagesArray[$i] = false;
        }                    
    }
}

And if $key equals to $i, I need to exit from loop. But in this case, break doesn't work and for loop goes on even if $key was found.

Why it goes like that?

Upvotes: 0

Views: 71

Answers (1)

Barmar
Barmar

Reputation: 782130

The for loop is unnecessary. Just use the keys of $request->photos as the keys to fill in $imagesArray.

$imagesArray = array_fill(1, 8, false);
foreach ($request->photos as $key => $photo) {
    dump($key);
    $path = storage_path('app/public/images/' . $pdf->id . '-' . $key . '.png');
    $image = Image::make($photo->getRealPath())->widen(300)->save($path);
    $imagesArray[$key] = true;
}

Upvotes: 2

Related Questions