PHP, what is the best way to handle a variable that cannot be set?

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

My question is related to the fact that I think that best practices, for example, are normal:

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

It seems useless to me, but in this case, if I do not, these are errors in the foreach. should i pass an empty array? I did not post specific code, because its a general question about handling variables that may or may not be set.

+4
source share
5 answers

Just note: here is the "safe" way.

 if (isset($array) && is_array($array)) { foreach ($array as $item) { // ... } } 
+8
source

Try:

  if(!empty($array)) { foreach($array as $row) { // do something } } 
+1
source

This is not dirty at all. This is actually the best practice. If I were to point out something dirty, that would be using the Allman bracket style, but that's a personal preference. (I'm a 1TBS guy);)

I usually do this in all methods of the class:

 public function do_stuff ($param = NULL) { if (!empty($param)) { // do stuff } } 

Word on a blank (). There are cases where isset is preferable, but an empty one works if the variable is not set, OR if it contains an "empty" value, for example, an empty string or the number 0.

0
source

If you pass an empty array to foreach, then this is fine, but if you pass an array variable that is not initialized, it will result in an error.

It will work when the array is empty or not even initialized.

 if( !empty($array) && is_array($array) ) { foreach(...) } 
0
source

I would say that it is good practice to have a β€œlogical” other value that is set as 0 (PHP false) to run, and whenever a function adds this array, add +1 to the logical value, You have a certain way to find out if you need to mess around with the array or not?

That the approach I would use in an object-oriented language in PHP might be more messy, but still I think it's better to have an intentional variable, tracking, rather than trying to parse the array itself. Ideally, if this variable is always an array, set the first value to 0 and use it as a flag:

  <?PHP //somewhere in initialization $myArray[0] = 0; ... //somewhere inside an if statement that fills up the array $myArray[0]++; $myArray[1] = someValue; //somewhere later in the game: if($myArray[0] > 0){ //check if this array should be processed or not foreach($myArray as $row){ //start up the for loop if(! $skippedFirstRow){ //$skippedFirstRow will be false the first try $skippedFirstRow++; //now $skippedFirstRow will be true continue; //this will skip to the next iteration of the loop } //process remaining rows - nothing will happen here for that first placeholder row } } ?> 
-1
source

All Articles