Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - Extract an associative array

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.

like image 746
tika Avatar asked Mar 14 '23 06:03

tika


1 Answers

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.

like image 165
Mikel Bitson Avatar answered Mar 25 '23 05:03

Mikel Bitson