Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unset( ) not working PHP

Tags:

php

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>   
like image 910
Hugo Avatar asked Oct 23 '13 08:10

Hugo


2 Answers

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)

like image 196
Henk Jansen Avatar answered Sep 19 '22 06:09

Henk Jansen


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',
...
)
like image 40
MAQU Avatar answered Sep 21 '22 06:09

MAQU