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.
$ball
and$cat
are defined in scope (before extract) and thus they still exist. This is why they do not work in function. The Array has no index to assign to the variable when running extract. .$cat
and$ball
have the same value as keys0
and1
in the array, butextract
is actually skipping the numeric indexesextract()
. Iterate your Array and collect the data manually into variable instead of usingextract()
to ensure you get the values.$data
, you may have to get a mapping array, saying what is the variable order expected... in order to say "1st value is APPLE, 2nd will be BALL, and 3rd will be CAT"... and then use this mapping array to extract data manually...