Cryssie
Cryssie

Reputation: 3175

Check if an array's elements exists in another array in PHP

I would like to check if an element from one array already exists in another array. If it exists then I would like to add all elements from the first array to a new associative array and add one additional key-value ([check] => 0/1) to indicate that the element exists or not in another array.

This is a sample code of what I tried.

$first = array("0"=> 111, "1"=>222, "2"=>333, "3"=> 444);
$second = array("0"=> 22, "1"=>234, "2"=> 456);

$final_array = array();

foreach($first as $f)
{
    if(in_array($f, $second))
    {
        $final_array['id'] = $f;
        $final_array['check'] = 1;
    }

    else 
    {
        $final_array['id'] = $f;
        $final_array['check'] = 0;
    }
}

For some reasons I am only able to add the last element to the $final_array. Can someone tell me what I did wrong?

//Output for $final_array
Array ( [id] => 444 [check] => 0 )

//final output should look like this
$final_array = array("0"=> array("id" => 111, "check" => 0), 
                    "1" => array("id" => 222, "check" => 1), 
                    "2" => array("id" => 333, "check" => 0), 
                    "3" => array("id" => 444, "check" => 0));

Upvotes: 1

Views: 3189

Answers (1)

Kevin
Kevin

Reputation: 41885

Since your expecting to push multiple items, you need to add another dimension inside:

$first = array("0"=> 111, "1"=>222, "2"=>333, "3"=> 444);
$second = array("0"=> 222, "1"=>234, "2"=> 456);

$final_array = array();
foreach($first as $f) {
    $temp = array('id' => $f);
    if(in_array($f, $second)){
        $temp['check'] = 1;
    } else {
       $temp['check'] = 0;
    }
    $final_array[] = $temp;
}

Or just simply like this using a ternary:

$final_array = array();
foreach($first as $f) {
    $final_array[] = array('id' => $f, 'check' => in_array($f, $second) ? 1 : 0);
}

What happens is that your values gets ovewritten each iteration:

$final_array['id'] = $f; // overwritten
$final_array['check'] = 1; // overwrriten

You need to push it with another dimension: $final_array[] = the array

Upvotes: 2

Related Questions