Reputation: 777
Hey guys im trying to search an array for an value and then remove it. But im searching with a php variable and that seems to be the problem. So this is what I have so far:
if(isset($_REQUEST['Admin'])){
$arr = array('HAUGMA1', 'sdasd', 'dasdasda', 'sadasd');
$key=array_search($_REQUEST['Admin'],$arr);
if($key!==false)
unset($arr[$key]);
print_r($arr);
}
The $_REQUEST
retrieves the value HAUGMA1
but when I print out the array it didn't remove HAUGMA1
from it. What am I doing wrong? When I'm using this:
$key=array_search('HAUGMA1',$arr);
It is working.
Upvotes: 0
Views: 137
Reputation: 1965
I think the problem is in relation to the value that is coming from the $_REQUEST
variable.
I made the following test to show two questions:
//Array definition
$arr = array('HAUGMA1', 'sdasd', 'dasdasda', 'sadasd');
//Search
$admin = 'dasdasda';
/* First sample */
$time = microtime();
$arr = array_filter($arr, function($key) use($admin) {
return $key != $admin;
});
print_r($arr);
echo '<br>Execution time: '.(microtime()-$time).'<br>';
/* Second sample */
$time = microtime();
$key = array_search($admin, $arr);
if($key !== false)
unset($arr[$key]);
print_r($arr);
echo '<br>Execution time: '.(microtime()-$time).'<br>';
First: using the array_search
has approximately 4x faster than array_filter
.
Second: the way that your script is, the item is removed from the array without problem. Try to debug the value that is coming from the variable $_REQUEST
Upvotes: 1
Reputation: 19879
array_search is case sensitive. Use strtoupper and trim in order to conform the incoming variable to the values in your array. trim() will get rid of trailing white space and other unwanted characters.
if(isset($_REQUEST['Admin'])){
$arr = array('HAUGMA1', 'SDASD', 'ETC');
$key = array_search(strtoupper(trim($_REQUEST['Admin'])), $arr);
if($key !== false){
unset($arr[$key]);
}
print_r($arr);
}
Upvotes: 0
Reputation: 2596
When i set manually $_REQUEST['Admin']
to "HAUGMA1", it's working. Are you sure there is no whitespace in the beginning or the end of your string ?
Try with this :
$key = array_search(trim($_REQUEST['Admin']), $arr);
Upvotes: 0
Reputation: 7887
try this (closure PHP >= 5.3)
$admin = $_REQUEST['Admin'];
$arr = array_filter($arr, function($key) use($admin) {
return $key != $admin;
});
Upvotes: 0