-4

I have an array

$array = ['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good'];

and I want to delete only one item from this array with matching key, like the following:

unset($array['f']);

However, this will delete the all items with this matching key 'f' and only one item will remain. Is there a way to do something like this, but apply it only to the first matching item in the array?

user101289
  • 9,888
  • 15
  • 81
  • 148
Feci
  • 11
  • 1
  • 3
  • you have a syntax error, but besides this your last `f` will over write all of your other defined `f` items in your array already, so there is no need to delete the others. – cmorrissey Oct 11 '16 at 20:09
  • 1
    You can't have the same key multiple times! – Rizier123 Oct 11 '16 at 20:09
  • @Rizier123 ... you can, they just overwrite eachother – cmorrissey Oct 11 '16 at 20:10
  • i have asked this because i am developing cart, with this class Cart `class Cart{ $totalqty, $totalPrice , $items }` and i add the Products in $items showing 5 elements of id 7 but if i delete one this delete all – Feci Oct 11 '16 at 20:48
  • use the real code, and the real data, or we cant help –  Oct 11 '16 at 20:50

3 Answers3

1

First of all you have a syntax error.

$array=$array(['f'=>'foo', 'f'=>'foo', 'f'=>'foo','g'=>'good']);

You have an $ extra and [] extras, and you can't have a lots off records with the same key(because the last one will override the previously)... The correct way to define

$array= array('f'=> array('foo', 'foo2', 'foo3'), 'g'=>'good');

The values will be a new array inside de F key. And then you can remove only one record

unset($array['f'][0]);

now your arrays var_dump:

$array= array('f'=> array('foo2', 'foo3'), 'g'=>'good');
TacticJuls
  • 304
  • 1
  • 8
  • thanks for your assistance, when i was using this `unset($array['f'])` this was removing elements matching to that key, but now with `unset($array['f'][0])` – Feci Oct 11 '16 at 20:22
  • now with `unset($array['f'][0])` this is not deleting any element from the array – Feci Oct 11 '16 at 20:23
  • No problem @feci, if you want to delete other element from F you have to change the number... [0] for ex: $array['f'][1] – TacticJuls Oct 11 '16 at 20:41
  • Then what to do now – Feci Oct 11 '16 at 20:42
0

i have solved this by using this as per cmorrissy comment there will be only one item so that variable was showing me qty, i have to check if

if($product[$id]['quantity']>1){ $product[$id]['quantity']--;}else{unset($product[$id]);}

Feci
  • 11
  • 1
  • 3
0

if you var_dump($array); this would be the output

var_dump($array);
array(
    f => foo
    g => good
 )

since you have an array with the same index it will be displayed as one, and thats why it will be deleted