Arihant Arihant - 1 month ago 10
PHP Question

How to compare two arrays and show matches in columns

I have two arrays.

Array 1 - List of all dates

Array 2 - list of all dates a person is present

I want to show a table that has all the dates in the first row and at each day that a person is present on the second row, the respective column should say present.

I tried nested loop but it just shows various rows and one result per row i.e. only one match per row.

I want to accomplish something like this



<table width="100%" border="1" cellspacing="1" cellpadding="1">
<tr>
<td width="6%">160111</td>
<td width="6%">160113</td>
<td width="6%">160120</td>
<td width="6%">160127</td>
<td width="6%">160201</td>
<td width="6%">160203</td>
<td width="6%">160208</td>
<td width="6%">160210</td>
<td width="6%">160217</td>
<td width="6%">160224</td>
<td width="6%">160229</td>
<td width="6%">160302</td>
<td width="6%">160307</td>
<td width="6%">160309</td>
<td width="6%">160321</td>
<td width="5%">160323</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>Present</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>Present</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>Present</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>





Suggestions? How to run loop or how can this be achieved?

Answer

Use in_array() to test whether an item is in Array 2.

foreach ($array1 as $day) {
    echo "<td>";
    echo in_array($day, $array2) ? "Present" : "&nbsp;";
    echo "</td>";
}