0

I have two arrays, I want to print values from both, if the key is present in $array_two

example code :

$array_one = [
    'one' => 'foo',
    'two' => 'bar'
];

$array_two = [
    'one' => 'view_foo',
];

I use this code

foreach($array_one as $array_key_one => $val_array_one)
{
    foreach($array_two as $array_key_two => $val_array_two)
    {
        if($array_key_one == $array_key_two)
        {
            echo $val_array_two;
        }
        else
        {
            echo $val_array_one;
        }
    }
}

But i want to use only one foreach

The desired results

bar, view_foo

How to solve it?

2 Answers 2

4

What if:

foreach($array_one as $array_key_one => $val_array_one)
{
    if(isset($array_two[$array_key_one] ))
    {
       echo $array_two[$array_key_one];
    }
    else
    {
       echo $val_array_one;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could intersect the array keys and then iterate over the results:

foreach (array_intersect_key($array1, $array2) as $key => $value1) {
    echo $value1, ' ', $array2[$key], ' ' ;
} 

array_intersect_key returns an array containing all the entries of array1which have keys that are present in all the arguments.

Comments

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.