phparrayskeyassociative-arraymerging-data

Append numerically-keyed elements to an numerically-keyed array without overwriting pre-existing elements


I've been going back and forth with in_array and for loops, but haven't quite been able to accomplish what I've been trying to do...

I have an array (named $contacts) that looks like this:

Array
(
    [3] => 1
    [5] => 1
    [7] => 1
)

I'm trying to add additional key => value pairs based on results from a query:

//query results
+------+------+
| uid  | nid  |
+------+------+
|    1 |   24 |
|    3 |   23 |
|    4 |   22 |
|    5 |   28 |
|    6 |   29 |
|    7 |   30 |
|    8 |   27 |
+------+------+

What I'm trying to do is if the uid is not in the $contacts array keys, then I want to add it with a value of "0", so that the end result is this:

Array
(
    [3] => 1
    [5] => 1
    [7] => 1
    [1] => 0
    [4] => 0
    [6] => 0
    [8] => 0
)

Solution

  • Did you try something like:

    if (!isset($contacts[1]))
        $contacts[1] = 0;