Jump to content

Unset not working in PHP 5.5 but works in PHP 7


sKunKbad
Go to solution Solved by sKunKbad,

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.