Pages

Wednesday, December 28, 2011

Removing Values from a PHP Array

I found myself needing to remove a couple of values from a PHP array. There's currently no PHP function that removes a value from an array, but there's a way around it.

You're going to need the following functions:
  • array_search
  • unset

ARRAY_SEARCH
The array_search function, can take up to three arguments. But you'll only need 2 for this to work.

syntax: array_search (needle, haystack);

where 
  • needle = what you're searching for
  • haystack = where you're searching from
 This functions returns the array key of the first occurrence of the needle in the haystack (there may be multiple occurrences)


UNSET
The Unset function unsets the value of a variable.

Therefore, to remove values from an array, one would do something like this:
<?php
$emails = array ('hello@world.com', 'hi@hello.com', 'greetings@greet.com');
$find = 'hello@world.com';

$key = array_search($find, $emails);
unset($emails[$key]);

?>

You're done! Obviously, if you have to find many emails, you'd have to put those emails in an array, and do a foreach. Something like this:


<?php
$emails = array ('hello@world.com', 'hi@hello.com', 'greetings@greet.com');
$find = array( 'hello@world.com', 'hi@hello.com');

foreach($find as $find_email)
{
     $key = array_search($find_email, $emails);
     unset($emails[$key]);
}
?>

Easy isn't it?

No comments:

Post a Comment