begineeeerrrr begineeeerrrr -3 years ago 161
PHP Question

Laravel, best way to compare key and value of array(s)

Currently I have 2 arrays as shown in the picture below. What is the best way to compare them? Either by combining them together and compare within one array or compare the way I did?

$array1

$array1

$array2

enter image description here

This is what i did to compare them

<table>
<thead><tr><td>status</td></tr></thead>

<tbody>
<tr>
<td>
foreach($array1 as $key => $value)
{
foreach($array2 as $ke2 => $value2)
{
if($value[0] == $value2[0] &&
$value[1] == $value2[1] &&
$value[2] == $value2[2])
YES
else
NO
}
}
</td>
<tr>
</tbody>
</table>


updated

<table>
<thead><tr><td>status</td></tr></thead>

<tbody>
<tr>
<td>
@foreach ($array1 as $key => $value)
@if (isset($array2[$key]) && $value == $array2[$key])
Yes
@else
No
@endif
@endforeach
</td>
<tr>
</tbody>
</table>


but this display in the table like this

Status

NoYesYes

NoYesYes

NoYesYes

Suppose to be

Status

No

Yes

Yes

Answer Source

Equivalency works for arrays, so you can eliminate the inner foreach loop

foreach ($array1 as $key => $value) {
    echo isset($array2[$key]) && $value == $array2[$key] ? 'YES' : 'NO';
}

You can also use === for typesafe comparisons and where the order of keys is important. See also: Compare multidimensional arrays in PHP

If you're looking for how to output into a template, Blade has its own syntax for loops and conditionals.

@foreach ($array1 as $key => $value)
    @if (isset($array2[$key]) && $value == $array2[$key])
        Yes
    @else
        No
    @endif
@endforeach

Check the documentation page for more on Blade templating syntax: https://laravel.com/docs/5.4/blade#loops

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download