PHP

PHP Remove Value From Array Examples

While dealing with arrays in PHP, there could be times when you would want to remove a specifc value from array, once you know what that value is. This could help you retain only the data that you want in the array. So do you know how to use PHP to remove value from array? If not, this article is for you. In this article, I am going to share very easy ways to to remove single value or remove multiple values from array using PHP by means of examples.

How To Remove Value From Array Using PHP

Let’s assume that we have an array. For the sake of the example, let’s assume that we have an array of fruit names. Now we will see how easily we can delete an array value, provided we know the value that we wish to remove.  Let’s assume that in the fruits array, we want to remove the array value “grapes”.

Example 1 – Remove specific value from array by using its value

<?php 

echo 'Example 1: Removing a value from the array<br />';

//Declare an array
$my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple');

//Print the contents of the array.
echo 'Following are the original array contents:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

//Remove "grapes" value from array
if( ( $key = array_search('grapes', $my_fruits_array) ) !== false ) 
{
    unset($my_fruits_array[$key]);
}

//Print the contents of the array.
echo 'Following are the array contents AFTER removing the value from array:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

?>

Example 2 – Remove specific value from array using its value

<?php 

echo 'Example 2: Removing a value from the array<br />';

$my_fruits_array = array('apple', 'mango', 'grapes', 'pineapple');

//Print the contents of the array.
echo 'Following are the original array contents:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

//Remove "grapes" value from array
$my_fruits_array = array_diff($my_fruits_array, array('grapes'));

//Print the contents of the array. 
echo 'Following are the array contents AFTER removing the value from array:<br />';
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';

?>

That’s it!

Do you know of any other ways to use PHP to  remove value from array? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*