1

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));
1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

To be honest I self taught myself PHP from scratch and it seems I still have a long way to go. I never heard of ternary until today. Thank you so much.
@Cryssie ternary is just a simplified if else, don't worry you'll get the hang of it soon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.