Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between extract()'s constants: EXTR_PREFIX_SAME vs EXTR_PREFIX_IF_EXISTS

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.

like image 974
CartoonChess Avatar asked Oct 16 '25 17:10

CartoonChess


2 Answers

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.

like image 75
too much php Avatar answered Oct 18 '25 05:10

too much php


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
like image 38
jason Avatar answered Oct 18 '25 06:10

jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!