sergioviniciuss
sergioviniciuss

Reputation: 4696

how to use in_array for subarrays in php?

I need to verify if a value is inside an array, and I'm using the php function in_array() for it. I noticed it doesn't work when the array I send to the in_array() function is composed by subarrays. Is there anyway to do this verification for subarrays? To help you to understand my problem, I have the following code:

$userIds = array();
foreach($accounts as $account){
    $accounIds[] = $account->getId();
    $userIds[] = AccountUserBeanHome::findAllIdsByAccountId($account->getId());
}
$userId = 225;
if (in_array($userId, $userIds, true)) {
    do action...
}

The problem is that the array $userIds may be something like this:

Array
(
[0] => Array
    (
        [0] => 225
        [1] => 226
        [2] => 227
        [3] => 228
        [4] => 229
        [5] => 230
        [6] => 340
        [7] => 355
    )

[1] => Array
    (
        [0] => 313
        [1] => 314
        [2] => 315
        [3] => 316
        [4] => 318
        [5] => 319
    )

[2] => Array
    (
        [0] => 298
        [1] => 301
        [2] => 302
        [3] => 338
    )

)

I noticed in_array() doesnt work to check sub-arrays, so I'd like your help to do this verification... maybe a way to make all the subarrays elements become all elements of the main array... well.. I hope u can help me.

Upvotes: 2

Views: 8775

Answers (3)

Florent
Florent

Reputation: 12420

You can flatten $userIds array using array_merge():

$userIds[] = array();
foreach($accounts as $account){
    $accounIds[] = $account->getId();
    $userIds = array_merge($userIds, AccountUserBeanHome::findAllIdsByAccountId($account->getId()));
}

Then call in_array() to check your id.

Upvotes: 1

user657496
user657496

Reputation:

$iterator = new RecursiveIteratorIterator(
                new RecursiveArrayIterator($userIds), 
                RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $key => $val) {
    if($val == $userId) {
        // do something
    }
}

Documentation about recursiveiteratoriterator.

Kudo's to gordon

Upvotes: 2

Martijn
Martijn

Reputation: 3754

What you need is a recursive in_array. Luckily, many people have made this already.

This one is directly from the PHP manual comments section: http://www.php.net/manual/en/function.in-array.php#84602

<?php 
function in_array_recursive($needle, $haystack) { 
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack)); 
    foreach($it AS $element) { 
        if($element == $needle) { 
            return true; 
        } 
    } 
    return false; 
} 
?>

Upvotes: 12

Related Questions