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

392

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 iflevel1 orlevel2 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?

33

Answer

Solution:

Short of doing aneval, I don't think you can do it.

if(eval("!is_array($array".$dimension.")"))
    return false

However, this is another way to do it

function check_md_array($array,$array_levels){
    if(!is_array($array))
         return false;

    foreach($array_levels as $level){
        if(!isset($array[$level]) || !is_array($array[$level]))
            return false;
        $array = $array[$level];
    }

    return true;
}

People are also looking for solutions to the problem: php - Unable to send an associative array in JSON format in Zend to client

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.