Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove values from an array in PHP?

Tags:

php

Is there a PHP function to remove certain array elements from an array?

E.g., I have an array (A) with values and another array (B) from which a need to remove values.

Want to remove the values in array A from array B?

like image 872
Elitmiar Avatar asked Aug 17 '09 14:08

Elitmiar


People also ask

How do you remove values from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an element from an array with value?

We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


1 Answers

Use array_diff()

$new_array = array_diff($arrayB, $arrayA);

will return an array with all the elements from $arrayB that are not in $arrayA.

To do this with associative arrays use array_diff_assoc().

To remove a single value use:

unset($array[$key]);

You can of course loop that to do the equivalent of the array functions but there's no point in that.

like image 189
cletus Avatar answered Sep 20 '22 18:09

cletus