Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a value in an array and remove it by using PHP array functions?

How to find if a value exists in an array and then remove it? After removing I need the sequential index order.

Are there any PHP built-in array functions for doing this?

like image 203
DEVOPS Avatar asked Jun 17 '10 06:06

DEVOPS


People also ask

How do I remove a specific element from an array in PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically. Function Used: unset(): This function unsets a given variable.

How do you extract the value from the array in PHP?

The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

How do I remove an item from an array by value?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.


2 Answers

To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:

<?php $hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');  print_r($hackers);  // Search $pos = array_search('Linus Trovalds', $hackers);  echo 'Linus Trovalds found at: ' . $pos;  // Remove from array unset($hackers[$pos]);  print_r($hackers); 

You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.

like image 152
mohitsoni Avatar answered Oct 05 '22 13:10

mohitsoni


<?php $my_array = array('sheldon', 'leonard', 'howard', 'penny'); $to_remove = array('howard'); $result = array_diff($my_array, $to_remove); ?> 
like image 43
Peter Avatar answered Oct 05 '22 14:10

Peter