phpmultidimensional-arrayindexingdynamic-values

PHP dynamic array index name


I want to pass a function the index value of an array – e.g [‘client_name’] – a first level value works because I can do

        $index = client_name;

        function arraything ($index) { return $this->arraytolookat[$index]; }

The question is… how do I do this, if it’s a multi nested array?

I tried the eval statement and apparently it doesn’t evaluate brackets well … So I tried this.

        $index = “[0][‘client_name’]”;

        Eval(“$this->arraytolookat$index”);

But it just fails… winges about a unexpected [ - any Ideas?

EDIT: I do not know how many levels this function may be required to go into, therefore I cannot just append a set amount of brackets at the end. Its not as simple as it looks ^^

EDIT 2: Basically - I have written a form validation tool and one of the functions returns correct post data - I wanted a simple method that when you enter the name of the form element - it would literally return teh POST data back to the element e.g getFormData("client_name") - however when a form gets more complex, it can go into arrays, I need to prepare for the possibility of getFormData("['$i']client_name") or somthing along those lines, stuff happens to the postdata in that class so that function must be used. I just want that function to take in a string not an array.


Solution

  • You can pass an array of indexes to this function below. So if you would like to get $some_array[0]['client_name']['third_level_index'] then you can do this:

    function get_array_value(array $array, array $indexes)
    {
        if (count($array) == 0 || count($indexes) == 0) {
            return false;
        }
    
        $index = array_shift($indexes);
        if(!array_key_exists($index, $array)){
            return false;
        }
    
        $value = $array[$index];
        if (count($indexes) == 0) {
            return $value;
        }
    
        if(!is_array($value)) {
            return false;
        }
    
        return get_array_value($value, $indexes);
    }
    
    $some_array = array(/* nested array */);
    
    $indexes = array(0, 'client_name', 'third_level_index');
    
    $value = get_array_value($some_array, $indexes);