Search code examples
phparraysforeacharray-mergearray-unique

Combine 2 Arrays In Foreach in PHP


I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.

This is my username list from database.

$digits = [1,2,3,4];
$results = $db->table($usernames)
    ->where('memberID', $mID)->limit(10)
    ->getAll();

foreach ($results as $result) {
echo $result->userName;
}

I tried this:

$combined = array_merge($digits, $results);

foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
    {
        echo $single.'<br>';
        echo $results->userName;
    },
}

Solution

  • You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:

    $combined = array_combine($digits, $results);
    
    foreach ($combined as $digit => $result) {
            echo $digit . '<br>' . $result;
    }