13

I have tried many different ways but im not able to unset a variable from an array. I started with a string and exploded it to an array, now i want to remove Bill. Im i missing some thing? I have visited php.net and i, 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>   
Hugo
  • 659
  • 2
  • 7
  • 18

5 Answers5

19

That is because ['Bill'] is the value of the array entry, 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 :

PHP array delete by value (not key)

Community
  • 1
  • 1
Henk Jansen
  • 1,142
  • 8
  • 27
  • Thank every it makes scenes now..... I was able to accomplice what what i needed with the foreach loop. Thanks for the link 1intello – Hugo Oct 23 '13 at 12:07
1

Because unset expect a key and not a value.

Bill is your value.

unset($Allname[2])

after your explode the array looks like:

array (

0 => 'Harry',
1 => 'George',
2 => 'Bill',
...
)
MAQU
  • 562
  • 2
  • 12
  • If i dont know the position of bill i would use a foreach? – Hugo Oct 23 '13 at 09:17
  • 1
    there are several ways to do it. a foreach loop is possible but i would prefer `array_search()` to get the key of Bill. `$key = array_search('Bill', $Allname);` – MAQU Oct 23 '13 at 09:25
1

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

If you want to remove the value "Bill", it's easiest to do this:

$names            = 'Harry George Bill David Sam Jimmy';
$namesArray       = explode(' ', $names);
$namesWithoutBill = array_diff($namesArray, array('Bill'));
deceze
  • 510,633
  • 85
  • 743
  • 889
1
You can unset by array key
unset($Allname[2]);
Ranjitsinh
  • 49
  • 8
1

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

Or in any case check your array is really an array. I know it 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 output: It Is an Array.

Shlomtzion
  • 674
  • 5
  • 12