Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable When values are empty

Tags:

php

I have 2 blocks of code....

// 1st block

<div id="a1">
<?php

if (is_array($new_array) || is_object($new_array))
{
  foreach ($new_array as $name => $val)
   {
     echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
   }
}
unset($new_array);
?>
</div>

2nd block

<div id="a2">
    <?php

    if (is_array($new_array) || is_object($new_array))
    {
      foreach ($new_array as $name => $val)
       {
         echo $name . " : " . $val[0] . " , " . $val[1]. " , " . $val[2];
       }
    }
    unset($new_array);
    ?>
    </div>

Either 1st or 2nd Block will give empty results in a day. Means if Today , 1st block will give empty result & tomorrow 2nd Block will give empty result.... Alternatively....

Issue :

Today, Value is empty for 2nd block , it gave Notice: Undefined variable: new_array error , so I initialized this before 2nd block of code :

$new_array=''; 

it worked fine.... but tomorrow 2nd block code will give this result :

Warning: Illegal string offset , Fatal error: Uncaught Error: Cannot use string offset as an array

So i need to remove this code : $new_array=''; before 2nd block & i need to place before 1st block.....


1 Answers

What about to use if (isset($new_array)) {...} or to initialize it like array, $new_array = [];

You can add isset to other checks, like this:

if (isset($new_array) && (is_array($new_array) || is_object($new_array))) { .... }

More info about isset()

like image 130
MorganFreeFarm Avatar answered Dec 04 '25 14:12

MorganFreeFarm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!