PHP's extract()
function can take on one of several extract_types
. But what's the difference between extr_prefix_same
and extr_prefix_if_exists
? The manual makes it sound like, in either case, new variables will be prefixed if the variable name already exists.
When using EXTR_PREFIX_IF_EXISTS
, if the variable doesn't already exist then the prefixed version won't be created either. In this example:
function test() {
$a = 12345;
extract(array('a' => 1, 'b' => 2, 'c' => 3), EXTR_PREFIX_IF_EXISTS, 'my_');
var_export(get_defined_vars());
}
test();
$my_b
and $my_c
aren't created because $b
and $c
don't exist.
EXTR_PREFIX_SAME
will extract all variables, and only prefix ones that exist in the current scope.
EXTR_PREFIX_IF_EXISTS
will only extract variables that exist in the current scope, and prefix them with the desired prefix.
So, for example:
$foo = 'foo';
$bar = 'bar';
extract(array('foo' => 'moo', 'bar' => 'mar', 'baz' => 'maz'), EXTR_PREFIX_IF_EXISTS, 'prefix');
isset($prefix_foo); // true
isset($prefix_baz); // false
isset($baz); // false
While....
$foo = 'foo';
$bar = 'bar';
extract(array('foo' => 'moo', 'bar' => 'mar', 'baz' => 'maz'), EXTR_PREFIX_SAME, 'prefix');
isset($prefix_foo); // true
isset($prefix_baz); // false
isset($baz); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With