phpextractexistsprefix

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.


Solution

  • 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.