I'm having a little brain fart and I just want to double check something ...

// Array of [a,b,c,d]
$array = array('a', 'b', 'c', 'd');

// Loop through array
foreach ($array AS $letter)
{
    // Break out of the loop on a specific condition
    if ($letter == 'c')
    {
        break;
    }
}

echo $letter;

I just want to double check $letter's scope. $letter exists outside of the foreach loop and retains the value of 'c', right?

That's correct

Member Avatar for diafol

Scope is fine. Only an issue when set in a function. But you already knew that :)

scope is fine, but intent is not clear in my opinion :-/

If you plan to use a variable outside of a loop, it should be declared outside even if null. That way, in the future, some fool who has to read it will understand what you meant to do, and not think "oh, well this is obviously in the wrong place...."

Just my 2c.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.