I have a PHP array of associative arrays with the following format:
array(1) {
[0]=>
{ ["name"]=> "Steve Jobs"
["email"]=> "steve@gmail.com" }
}
I'm very new to PHP, but what I want to do is search for a specific email, and if found, delete that specific array (name & email pair) from the array (without leaving an empty space in the array where the removed object used to be).
I found this code here that searches for an entry but returns an array. How would I modify this to delete the found array?
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
Something like this?
function delete_user(&$arr, $name){
for($i = count($arr)-1; $i >= 0; $i--){
if($arr[$i]["name"] == $name){
unset($arr[$i]);
}
}
}
the &$arr
tells PHP to pass the array by reference, so it can be modified from the function, otherwise, it'll be pass-by-value.
You have to use unset to remove an element and use in_array or array_search method to search an element from an array.
unset($array[0]);
Sample from PHP manual (array_search)
function array_key_index(&$arr, $key) {
$i = 0;
foreach(array_keys($arr) as $k) {
if($k == $key) return $i;
$i++;
}
}
just found array index, and
unset(array(key));
this will not showing that array
I believe there's a small problem with raser's answer. I tried to comment on it, but I can't since I don't have 50 reputation.
Let me know if you agree: count($arr)
returns the number of elements in the array. He's using a decremental for
loop, except the array's index starts at 0
and his loop ends before it reaches 0
, so the first element of the array is never searched. I believe the correct code would be something like:
function delete_user(&$arr, $name){
for($i = count($arr) - 1; $i >= 0; $i--){
if($arr[$i]["name"] == $name){
unset($arr[$i]);
}
}
}
Thanks!