Is it possible to know if a two-dimensional array is empty?

Asked

Viewed 136 times

4

basically my doubt is already clarified in the question. That’s it, I wonder if it is possible to know if a two-dimensional array is empty?

Thank you in advance!

1 answer

2


Yes, it is possible.

In this example I make a loop in the array revenant and print all the arrays that compose it, which are not empty, that is, print all except the last array that composes the "main array".

So, you just need to check by the array key with the function empty() PHP if there are values associated with the internal array.

Example:

<?php

$revenant = array(
        'cast' => array(
            'Leading Role' => 'Leonardo DiCaprio',
            'Supporting Actor' => 'Tom Hardy'
        ),
        'overview' => array(
            'Movie' => 'The Revenant',
            'Director' => 'Alejandro Iñárritu',
            'Year' => '2015'
        ),
        'details' => array()
);

foreach($revenant as $key => $val){
    if(!empty($val)){
        print_r($val);
    }
}

  • 1

    Perfect, I would have done it that way before you answered. However I didn’t know if it was the right way since for simple array php already has function ready to take care of it.

  • 1

    Thank you very much!

  • No problem! Good luck!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.