Search code examples
phparraysmultidimensional-arrayis-empty

How to check an empty slot in 3 dimensional array in PHP?


I have coding about 3 dimensional array. I need a function to automatically check where the empty slot is, and then insert the empty array ($rhw[104][1][2]) values Class C.

The coding structure is,

$rhw[101][1][2] = "Class A";
$rhw[102][1][2] = "Class B";
$rhw[103][1][2] = "";

And i just can make like the coding below,

if (empty($rhw[103][1][2])) {
    echo "TRUE";
} else {
    echo "FALSE";
}

But there is already declared like --- if (empty($rhw[103][1][2])) --- I dont know how to automatically check where the empty slot is (which is $rhw[103][1][2]).

Such as,

if (empty($rhw[][][])) {
    insert "Class C";
} else {
    echo "The slot has been fulfilled";
}

But it can not be proceed.

Thank you, guys! :)


Solution

  • Taken from in_array() and multidimensional array

    in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
    
    function in_array_r($needle, $haystack, $strict = false) {
        foreach ($haystack as $item) {
            if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
                return true;
            }
        }
    
        return false;
    }
    

    Usage:

    $b = array(array("Mac", "NT"), array("Irix", "Linux"));
    echo in_array_r("Irix", $b) ? 'found' : 'not found';
    

    For check a particular position, you can use a more simple solution:

    if(isset($rhw[103]) && isset($rhw[103][1]) && isset($rhw[103][1][2]))
    {
        echo "TRUE";
    } 
    else 
    {
        echo "FALSE";
    }
    

    Or use a function for check isset for each multidimensional position.

    function check_multidimensional($data, $a, $b, $c)
    {
        return isset($data[a]) && isset($data[$a][$b]) && isset($data[$a][$b][$c]);
    }
    

    You can even make a more generic function for N dimensions.