php - Extract an associative array

tika

I am trying to extract a mixed associative array like:

<pre>
        <?php


        bar();

        function bar(){
            $apple = 6;
            $ball = 2;
            $cat = 3;

            $data = ["apple" => 1, $ball,$cat];

            foo($data);
        }

        function foo($data){
            extract($data);
            echo "<br />apple:" . $apple;
            echo "<br />ball:" . $ball;
            echo "<br />cat:" .  $cat;
        }

        ?>
</pre>

The $data array can be only numeric, only associative or both. If element of array misses an index, it should be same as the variable.

Mikel Bitson

This does not work in your function because $ball and $cat are not defined in the function scope. The extract() function will only assign the value to a variable if the value in the array has a key, which $apple does. This means that $apple will output in the function, but $ball and $cat would be undefined.

This happens because in order for extract() to know what to name the variable, there has to be a key in the array.

To do this, you either need to manually specify the keys in the array each time:

$apple = 6;
$ball = 2;
$cat = 3;
$data = ["apple" => $apple, "ball" => $ball, "cat" => $cat];

// Now, extracting from $data creates the variables we need...
// Unsetting the $apple, $ball, and $cat variables 
// allows us to see that extract is recreating them.
unset($apple, $ball, $cat);
extract($data);
echo $apple, $ball, $cat;

Or you need to check the $ball and $cat variables to see if they are arrays. If they are arrays, you could use their key in the array so that extract() knows what to name the variable it creates. Do you need to dynamically determine if a variable already has a key (is an array), or is this enough?

EDIT: This should not be done with extract(). Realistically, you should create a class and store this data within a class. Then, loading the class would give you this information. extract() is a dangerous and messy beast.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related