Use string to store statement (or part of a statement), and then add it to the code

Posted by Dean on Stack Overflow See other posts from Stack Overflow or by Dean
Published on 2011-02-16T15:22:26Z Indexed on 2011/02/16 15:25 UTC
Read the original article Hit count: 225

Filed under:

I use multidimensional arrays to store product attributes (well Virtuemart does, to be precise). When I tried to echo the sub-arrays value, if the sub-array did not exist PHP threw:

Fatal error: Cannot use string offset as an array

To get around this, I attempted to create a function to check on every array level if it is an actual array, and if it is empty (when trying on the whole thing at once such as: is_array($array['level1']['level2']['level3']), I got the same error if level1 or level2 are not actual arrays).

This is the function ($array contains the array to check, $array_levels is an array containing the names of the sub-arrays, in the order they should apper):

function check_md_array($array,$array_levels){
    if(is_array($array)){
        $dimension = null;  //This will store the dimensions string

        foreach($array_levels as $level){
            $dimension .= "['" . $level . "']"; //Add the current dimension to the dimensions string

            if(!is_array($array/* THE CONTENT OF $dimension SHOULD BE INSERTED HERE*/)){
                return false;
            }
        }           
        return true;
    }
}

How can I take the string contained in $dimensions, and insert it into the code, to be part of the statement?

© Stack Overflow or respective owner

Related posts about php