0

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?

Rory McCrossan
338k41 gold badges320 silver badges354 bronze badges
asked Apr 15, 2015 at 9:34

3 Answers 3

1
$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;
}
answered Apr 15, 2015 at 9:41
Sign up to request clarification or add additional context in comments.

Comments

1

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);
});

Online test

answered Apr 15, 2015 at 10:05

Comments

1
<?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);
?>
answered Apr 15, 2015 at 10:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.