Remove only one value in the array

Asked

Viewed 713 times

0

I have an array this way

$arr = array('10', '12', '10', '15', '18', '18', '7', '18', '18', '15');

Four times the value 18. I need to remove from it only one value, example 18, and it remains so:

$arr = array('10', '12', '10', '15', '18', '7', '18', '18', '15');

And that with any other number until zero and have no more number, example the 18, has no limit of numbers.

Like a shopping cart logic

I have 10 products number 18, if I remove one at a time, the number 18 is leaving the array

I hope it’s clearer now

  • You want to take the last?

  • What do you mean until zero? Each number can only appear up to 3 times? The logic is unclear.

  • Until zeroing would the array have no more elements? What is the logic for determining which element should come out? The one that repeats most? Please [Dit] the question and be clear in your doubt.

  • 1

    To reset is easy, delete the array :) Related https://answall.com/questions/27445/removendo-um-element-espec%C3%Adfico-em-um-array

  • This may be the case for array_unique - Removes duplicated values from an array

  • @Andersoncarloswoss Before zeroing would be the case, if I have four numbers in the array, I take it from one to zero, understood, as if it were a shopping cart

  • @bfavaretto - The numbers have no limit, I just need to remove one at a time if necessary, or even remove all but have to be one at a time, until zero

  • Okay, remove one by one as long as there are numbers. That’s clear. Now, how to define the order that should be removed? That you haven’t explained yet.

  • @Andersoncarloswoss, remove only one, regardless of the amount of times it repeats, every time I call the function it would remove a number I determined from the array

  • @Marcospaulo and how should the array indexes look after the value is removed? They should remain the same or readjust them?

  • @Andersoncarloswoss no matter how they return, just remove each one

  • 4
Show 7 more comments

1 answer

1


For this is found the position with the function array_search:

$posicao = array_search('18',$arr);

And then remove this position with the function unset:

unset($arr[$posicao]);

Or doing it all together:

unset($arr[array_search('18',$arr)]);

Example

  • Perfect, it worked out here just the way I needed it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.