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?
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.
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.
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.
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.
<?php $my_array = array('sheldon', 'leonard', 'howard', 'penny'); $to_remove = array('howard'); $result = array_diff($my_array, $to_remove); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With