I have an array like this, that could have any number of "domain" arrays. I've removed unnecessary keys in this example.
Array
(
[result] => success
[clientid] => 7
[numreturned] => 2
[domains] => Array
(
[domain] => Array
(
[0] => Array
(
[domainname] => example.net
)
[1] => Array
(
[domainname] => example.com
)
)
)
)
I need to figure out how to check this array to see if it contains a domain name.
I'm trying to do something like this:
if(arrayContains("example.com")){
$success = true;
}
I have tried a number of solutions I found on SO, but they don't appear to be working. One example I found used array_key_exists, which is kind of the opposite of what I need.
Any suggestions on how to do this?
3 Answers 3
Use this function to help you out:
<?php
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;
}
?>
This was found in one of the comments in the PHP doc about array_search()
.
Comments
$array = array(
"result" => "success",
"clientid" => 7,
"numreturned" => 2,
"domains" => array(
"domain" => array(
0 => array(
"domainname" => "somedomain.com",
3 => array(
"domainname" => "searchdomanin.com",
),
),
1 => array(
"domainname" => "extwam",
),
)
)
);
$succes = FALSE;
$search = 'searchdomanin.com';
array_walk_recursive($array, function($key, $value) use(&$success, &$search){
if($key === $search){
$success = TRUE;
}
},
[&$key ,&$val]);
if($success){
echo 'FOUND';
}
Works with whatever dimension array you have.
Comments
Try something like this:
$domains = $arr['domains'];
foreach($domains AS $domain)
{
foreach($domain AS $internal_arr)
{
if($internal_arr['domainname'] == 'example.net')
{
$success = true;
}
}
}
array_search()
? - php.net/manual/fr/function.array-search.php#91365