Jump to content
Sign in to follow this  
sKunKbad

Unset not working in PHP 5.5 but works in PHP 7

Recommended Posts

I'm having a problem unsetting an array element when in PHP 5.5, but only when it's a class property. See code:

<?php

/**
 * Works fine as procedural code
 */
$arr = [23213523, 3634634, 68486468];
$val = 3634634;
if( ( $key = array_search( $val, $arr ) ) !== FALSE )
{    
    unset( $arr[$key] );
}

echo '<pre>';
print_r($arr);
echo '</pre>';

/**
 * Works fine on PHP7, but not PHP5.5
 */
class Foo {

    public $arr = [23213523, 3634634, 68486468];

    public function bar()
    {
        $this->_unset_numeric_val('arr', 3634634 );
    }

    private function _unset_numeric_val( $property, $val )
    {
        if( ( $key = array_search( $val, $this->$property ) ) !== FALSE )
        {
            unset( $this->$property[$key] );
        }
    }

}

$foo = new Foo;
$foo->bar();

echo '<pre>';
print_r($foo->arr);
echo '</pre>';

On PHP7 the results are the same, but on PHP 5.5 unset doesn't work. What's the problem here? What happened between versions? I looked at the docs for unset, but didn't see anything.

Share this post


Link to post
Share on other sites

Figured it out. Just need to wrap $property in curly braces.

unset( $this->{$property}[$key] );
Edited by sKunKbad

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.