PHP: How to Remove a Value From an Array

This PHP tutorial and example will cover how to pull out a serialized array from a MySQL database, and then utilizing the array_search() function and unset() function to remove a value from an array. Here is the tutorial as a copy and paste function to remove a value from an array:

<?php
 function removeArrayValue($string, $array) {
  $array = unserialize($array); 
   if(($key = array_search($string, $array)) !== false) {
    unset($array[$key]);
   }

    return $array;
 }
?>

Assuming you have already pulled out your data from your MySQL database, the first step is to take your serialized PHP array and unserialize(). In this example we will take the array of participants for a tournament, and remove the member named “Michael”.

<?php 
 $member = 'Michael';
 $participants = $row['participants'];
  $participants = unserialize($participants);
   //now the array looks like this: ('John', 'Susan', 'Alex', 'Michael', 'Lucas', 'Henry')
?>


We have to unserialize the array to make it readable, and that will allow us to use array_search() to loop through the array and remove an entry.

<?php
 if(($key = array_search($member, $participants)) !== false) {
  unset($participants[$key]);
 }
?>


The logic behind this method is simple, with array_search having 2 parameters: array_search($string_to_look_for, $the_array_to_search). Since our $member variable is set to ‘Michael’, and the array we are looking through is $participants, if ‘Michael’ is a value found in $participants, unset the key in the array.

Here is the whole code in action, which unserializes a serialized array, looks for the value ‘Michael’ in the $participants array, unsets the key if it is found, and then serialize the new array and store it in the database:

$member = 'Michael' //the value to search for and remove from the array
$participants = unserialize($participants);
//the array now looks like ('John', 'Susan', 'Alex', 'Michael', 'Lucas', 'Henry')
				   
 if(($key = array_search($member, $participants)) !== false) {
   unset($participants[$key]);
 }
$participants = serialize($participants);
 $sql = "UPDATE `participants` SET members = '$participants'";
 mysql_query($sql);
?>

Here is a copy and paste version of this method on how to remove a value from a PHP array as a function:

<?php
 function removeArrayValue($string, $array) {
  $array = unserialize($array); 
   if(($key = array_search($string, $array)) !== false) {
    unset($array[$key]);
   }

    return $array;
 }

 //example
 $member = 'Michael';
 $memberList = array('John', 'Susan', 'Alex', 'Michael', 'Lucas', 'Henry');
 
 $memberList = removeArrayValue($member, $memberList);
?>

Have a question or comment on this tutorial to remove a value from a PHP array? Post it here.

Leave a Comment

Your email address will not be published. Required fields are marked *