hi i have following array
$langarr[0][0] = gb
$langarr[0][1] = 1
$langarr[1][0] = de
$langarr[1][1] = 2
$langarr[2][0] = fr
$langarr[2][1] = 3
$langarr[3][0] = it
$langarr[3][1] = 5
Now i wanna search to unset like
if(($keyy = array_search('de', $langarr[][0])) !== false) {
unset($langarr[$keyy]);
}
So i wanna search in the langarr[any][0]
and if matched I want to delete the whole dataset like unset($langarr[X]);
How can this be achieved?
3 Answers 3
$langarr = array();
$langarr[0][0] = "gb";
$langarr[0][1] = "1";
$langarr[1][0] = "de";
$langarr[1][1] = "2";
$langarr[2][0] = "fr";
$langarr[2][1] = "3";
$langarr[3][0] = "it";
$langarr[3][1] = "5";
// Get the key of search array
$value = recursive_array_search("de",$langarr);
// print the key
print_r($value);
// unset the array "de" which has key "1"
unset($langarr[$value]);
// print the resultant array
print_r($langarr);
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Comments
Use array_filter()
. It takes a (anonymous) function as the second argument. The function itself receives an array element as its argument. If that function returns false
, the array element is removed from the array.
So to take your example, if $needle
is 'de', the subarray is removed.
$langarr = array(
array('gb', 1),
array('de', 2),
);
$needle = 'de';
$langarr = array_filter($langarr, function($row) use($needle) {
return ($row[0] != $needle);
});
Comments
<?php
$langarr[0][0] = "gb";
$langarr[0][1] = 1;
$langarr[1][0] = "de";
$langarr[1][1] = 2;
$langarr[2][0] = "fr";
$langarr[2][1] = 3;
$langarr[4][0] = "it";
$langarr[4][1] = 4;
print_r($langarr);
foreach($langarr as $key=>$data){
if($data[0]=='de'){
unset($langarr[$key]);
}
}
print_r($langarr);
?>