Unset () does not work PHP

I tried many different ways, but I could not disconnect the variable from the array. I started with a string and blew it into an array, now I want to remove Bill. Did I miss something? I visited php.net and I am still stuck ...

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php $names = "Harry George Bill David Sam Jimmy"; $Allname = explode(" ",$names); unset($Allname['Bill']); sort($Allname); $together = implode("," ,$Allname); echo "$together"; ?> </body> </html> 
+7
php
source share
5 answers

This is because ['Bill'] is the value of the array record, not the index. What you want to do is

 unset($Allname[2]); //Bill is #3 in the list and the array starts at 0. 

or see this question for a more detailed and better answer:

default PHP array (not key)

+12
source share
  You can unset by array key
 unset ($ Allname [2]);
+2
source share

Because unset expects a key, not a value.

Bill is your value.

 unset($Allname[2]) 

after your explosion, the array looks like this:

 array ( 0 => 'Harry', 1 => 'George', 2 => 'Bill', ... ) 
+1
source share

unset($arr['key']) disables the key. Your keys are 0 , 1 , etc., not Bill.

If you want to remove the value "Bill", this is easiest to do:

 $names = 'Harry George Bill David Sam Jimmy'; $namesArray = explode(' ', $names); $namesWithoutBill = array_diff($namesArray, array('Bill')); 
+1
source share

Sometimes it looks like an array, but it can be a printed string of the array ... - This happens to the best of us ...

Or, in any case, check that your array is an array. I know this sounds silly, but sometimes after many hours of screen time, mistakes are made.

 <?php $MyArray = array('0' => 'this','1' => 'is','2' => 'an array'); echo is_array($MyArray) ? 'It Is an Array' : 'not an Array'; ?> 

This will lead to the conclusion: this is an array.

0
source share

All Articles