Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP what is the best way to handle a variable that may not be set?

Tags:

php

I have a foreach loop, that will loop through an array, but the array may not exist depending on the logic of this particular application.

My question relates to I guess best practices, for example, is it ok to do this:

if (isset($array))
{

    foreach($array as $something)
    {
        //do something
    }
}

It seems messy to me, but in this instance if I dont do it, it errors on the foreach. should I pass an empty array?? I haven't posted specific code because its a general question about handling variables that may or may not be set.

like image 422
Tim Avatar asked Feb 27 '23 11:02

Tim


2 Answers

Just to note: here is the 'safest' way.

if (isset($array) && is_array($array)) {
    foreach ($array as $item) {
        // ...
    }
}
like image 92
strager Avatar answered Mar 01 '23 01:03

strager


Try:

 if(!empty($array))
 {
     foreach($array as $row)
     {
         // do something
     }
 }
like image 35
Manie Avatar answered Mar 01 '23 01:03

Manie