PASSWORD RESET

Your destination for complete Tech news

PHP

How to delete an element from an array in PHP?

389 0
< 1 min read

To delete an element from an array in PHP, you can use the unset() function. This function takes the element you want to delete as its argument and removes it from the array.

Here is an example of how to use unset() to delete an element from an array:

$array = array(1, 2, 3, 4, 5);

// Delete the element at index 2
unset($array[2]);

// The array now contains [1, 2, 4, 5]

You can also use the array_splice() function to delete an element from an array. This function takes the array, the start index, and the number of elements to delete as arguments. It returns an array containing the deleted elements.

Here is an example of how to use array_splice() to delete an element from an array:

$array = array(1, 2, 3, 4, 5);

// Delete the element at index 2
$deleted = array_splice($array, 2, 1);

// The array now contains [1, 2, 4, 5]
// $deleted contains [3]

You can also use the array_filter() function to delete elements from an array based on a condition. This function takes the array and a callback function as arguments. The callback function should return TRUE for elements that should be kept in the array and FALSE for elements that should be deleted.

Here is an example of how to use array_filter() to delete elements from an array:

$array = array(1, 2, 3, 4, 5);

// Delete even elements
$array = array_filter($array, function($value) {
    return $value % 2 != 0;
});

// The array now contains [1, 3, 5]

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.