jumpman8947
jumpman8947

Reputation: 581

Looping though arrays dealing with null values

I have an array myArray

Array ([0] =>(
         Number => 02348
         Food => Array (
             [0] => orange
             [1] => apple
             [2] => plum )
         State => Array (
             [0] => california
             [1] => texas
             [2] => arizona )
        Status => good )
       [1] =>(
         Number => 34
         Food => Array (
             [0] => grape
             [1] => bannana
             [2] => tomato )
        Status => rotten )
        [2] =>(
         Number => 007
         Food => Array (
             [0] => oranges
             [1] => apples
             [2] => plums )
         State => Array (
             [0] => ohio
             [1] => utah
             [2] => vermont )
        Status => good )

I am looping though my array and then grabbing the fields i need.

for($index=0; $index < count($myArray); $index++){
   $food = array_values(array_filter($myArray[$index]["Food"]));
   $states = array_values(array_filter($myArray[$index]["State"]));

For the $states line i get an error of

Notice: Undefined index: State 
Warning: array_filter() expects parameter 1 to be array, null given

As you can see in my array State may not always be present, is there a way to get around this. Also there is a large amount of data is being pulled dynamically and it would be difficult to change the structure of the array. How can i loop though my array ignoring nulls but still keeping the place of State. For example

State => Array (
         [0] => ohio
         [1] => utah
         [2] => vermont )

would still be mapped to the [2], and not shifted to [1].

Upvotes: 1

Views: 49

Answers (1)

mistajolly
mistajolly

Reputation: 481

$states = array_values(array_filter($myArray[$index]["State"]));

Using the above example from your code, the array_filter function expects an array so you will need to check that the variable $myArray[$index]["State"] passed to the function is both set and also an array. This will remove the notices and warnings.

You can test for an array using the is_array() function and test if a variable is set using the isset() function.

In this example, an intermediate variable $states_array is set using data from your array. It checks if the original variable is valid, otherwise, it is set to an empty array. This is then passed into the array_filter function.

$states_array = (isset($myArray[$index]["State"]) && is_array($myArray[$index]["State"])) ? $myArray[$index]["State"] : array() ;
$states = array_values(array_filter($states_array));

You may also be interested to know that PHP 7 provides a null coalesce operator which may be helpful when handling variables that may or may not be set.

See:

http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Upvotes: 1

Related Questions