Based on the manual definitions, EXTR_PREFIX_SAME
will create variables based on the key name, and if a variable in the local space already exists, a prefix will be added to the variable name.
By contrast, EXTR_PREFIX_IF_EXISTS
would appear to inherit the behavior of EXTR_IF_EXISTS
(only overwrite if the variables already exist), but instead of overwriting the local variables, a prefixed version will be created.
Consider the following
$array = Array();
$array['foo'] = 'foo';
$array['bar'] = 'bar';
$array['baz'] = 'baz';
$foo = 'local foo';
$bar = 'local bar';
extract($array, EXTR_PREFIX_SAME, 'pre');
print_r(get_defined_vars());
//partial output
//Array
//(
// [array] => Array
// (
// [foo] => foo
// [bar] => bar
// [baz] => baz
// )
//
// [foo] => local foo
// [bar] => local bar
// [pre_foo] => foo
// [pre_bar] => bar
// [baz] => baz
//)
So with EXTR_PREFIX_SAME
, the values of $foo and $bar will remain the same, and three new local variables ($pre_foo, $pre_bar, and $baz) will be defined. However if we use EXTR_PREFIX_IF_EXISTS
$array = Array();
$array['foo'] = 'foo';
$array['bar'] = 'bar';
$array['baz'] = 'baz';
$foo = 'local foo';
$bar = 'local bar';
extract($array, EXTR_PREFIX_IF_EXISTS, 'pre');
print_r(get_defined_vars());
//partial output
//Array
//(
// [array] => Array
// (
// [foo] => foo
// [bar] => bar
// [baz] => baz
// )
//
// [foo] => local foo
// [bar] => local bar
// [pre_foo] => foo
// [pre_bar] => bar
//)
The values of $foo and $bar are still preserved, but only TWO new variables are imported into the local space. Since $baz isn't a variable that already exists the EXTR_PREFIX_IF_EXISTS
tells PHP to ignore the 'baz' key in the array.