sKunKbad Posted October 14, 2016 Share Posted October 14, 2016 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. Quote Link to comment https://forums.phpfreaks.com/topic/302327-unset-not-working-in-php-55-but-works-in-php-7/ Share on other sites More sharing options...
Solution sKunKbad Posted October 14, 2016 Author Solution Share Posted October 14, 2016 (edited) Figured it out. Just need to wrap $property in curly braces. unset( $this->{$property}[$key] ); Edited October 14, 2016 by sKunKbad Quote Link to comment https://forums.phpfreaks.com/topic/302327-unset-not-working-in-php-55-but-works-in-php-7/#findComment-1538269 Share on other sites More sharing options...
requinix Posted October 14, 2016 Share Posted October 14, 2016 PHP 7 changed how syntax like that gets interpreted. Quote Link to comment https://forums.phpfreaks.com/topic/302327-unset-not-working-in-php-55-but-works-in-php-7/#findComment-1538272 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.