Julie Julie - 7 months ago 10
PHP Question

foreach function for more than 2 array

I need to insert data to a table.. the data come from different sources. The following are my code.

$title = array(Book A, Book B, Book C);
$number = array(2,1,4);
$lines = array(Maria, Smith, Abner);

for($i=1; $i<count($lines); $i++)
{
print '<tr>';
print '<td>'.$title[$i].'</td>';
print '<td>P'.$number[$i].'</td>';
print '<td>['.$lines[$i].']</td>';
print '<td></td>';
print '</tr>';
}


Seems not working :/ the array not display properly in my table.

I'm expecting output as follows:

------------------------------------------------
| Title | No | Lines | Remarks |
------------------------------------------------
| Book A | 2 | Maria | |
| Book B | 1 | Smith | |
| Book C | 4 | Abner | |
------------------------------------------------


at the moment.. I get the following output:

------------------------------------------------
| Title | No | Lines | Remarks |
------------------------------------------------
| Book A | 2 | Maria | |
| | | Smith | |
| | | Abner | |
------------------------------------------------

Answer

If your arrays has different keys you can 'reset' them to be zero-based. Just use $array = array_values($array). Quote from manual

array_values() returns all the values from the array and indexes the array numerically.

After this you code will work. This is how your example can be modified:

$title = array('Book A', 'Book B', 'Book C');
$number = array(2,1,4);
$lines = array('Maria', 'Smith', 'Abner');
/* At this point you have some arrays with unknown keys.
   It can be [0 => item, 1 => item2] or ['name' => item, 'name2' => item2]
   or even with skipped keys [0 => item, 7 => item2]
*/


// Reset keys for all arrays. Now all arrays will contain keys 0, 1, 2 etc.
$title = array_values($title);
$number = array_values($number);
$lines = array_values($lines);

for($i = 0; $i < count($lines); $i++) // Note, arrays now are zero-based, you must start from $i = 0
{
    print '<tr>';
    print '<td>'.$title[$i].'</td>';
    print '<td>P'.$number[$i].'</td>';
    print '<td>['.$lines[$i].']</td>';
    print '<td></td>';
    print '</tr>';
}