I was trying to figure out the behavior of EXTR_PREFIX_IF_EXISTS flag in extract() function. But when I run my code, it adds more than the desired number of variables(two in this case) to current symbol table as indicated by the line:variables added. The output indicates three variables were added instead of two and variable 'key3' exists. Now I can't figure out what's causing this behavior or whether I misunderstood this concept. I'm new to PHP. Any help will be really appreciated.
my code:
$key1 = 'old';
$key2 = 'old';
$my_array = array (
'key1' => 'new value1',
'key2' => 'new value2',
'key3' => 'new value3'
);
$num = extract ($my_array, EXTR_PREFIX_IF_EXISTS, "prefixed");
echo "variables added:$num<br />"; //number of variables imported to symbol table
echo isset($key1) ? 'TRUE': 'FALSE';
echo "<br />";// true
echo isset($prefixed_key3) ? 'TRUE': 'FALSE';
echo "<br />";
echo isset($key3) ? 'TRUE': 'FALSE';// should output false
output:
variables added:3
TRUE
FALSE
TRUE
print_r(get_defined_vars());which will show you what variables are defined (and so which ones you create)print_rshouldn't have changed the output... the behaviour you were seeing was definitely incorrect, you should only see that behaviour with theEXTR_PREFIX_SAMEflag. This demo on rextester demonstrates the correct behaviour of each flag.EXTR_PREFIX_SAME. One wonders if OP had changed the flag but then not uploaded the new code???