Delete equal values within a dynamic array

Asked

Viewed 372 times

3

I have an array with several dynamic names that can change each time, what is the most correct way to go through this array and create a condition to delete them iguail? (in the case of two items with the same name)

I had already seen something similar here but it was for fixed elements, I wanted to create a condition in which I said unset(command to remove an element from the array) in the repeated element, an example of what I want more or less below:

$array = ('pepsi','Coca','fanta','pepsi');
// verificaria se tem elemento igual
if( "a operação que estou na duvida"){
//daria unset em um dos valores duplicados
    unset($array["3"]);
} 
// uso pra ignorar as chaves do array e alinhar 
$array = array_values( $array );

Note: The values for example only, my array can have n values.

1 answer

2


php already has a function that does everything you want:

array_unique($array);

It removes duplicates and reorders the indices of the array.

See working on Ideone.

  • Gosh, I wasn’t aware of that function, thank you !

Browser other questions tagged

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