display two different sizes array in table

Viewed 81

I have two different sized arrays and want to display them side by side in the same table.

I tried to run both arrays in a loop but the issue is the shorter array runs out of index.

Here's what I tried:

$clean_s = ['apple','ball','cat','dog'];
$clean_r = ['apple','bat','carrot','duck','elephant','fan'];
if(sizeof($clean_s) == sizeof($clean_r)) {
        $max = sizeof($clean_s);
} else {
        $max = sizeof($clean_s) > sizeof($clean_r) ? sizeof($clean_s) : sizeof($clean_r);
}

$table = '<table><thead><tr><th>Source</th><th>Result</th></thead><tbody>';
for($i=0; $i < $max; $i++) {
   $table .= '<tr><td>'.$clean_s[$i].'</td><td>'.$clean_r[$i].'</td></tr>';
}

Output needed:

Source    |   Result
________________________
apple     |   apple
ball      |   bat
cat       |   carrot
dog       |   duck
          |   elephant
          |   fan
2 Answers

You can check isset() before the echo as:

$table = '<table><thead><tr><th>Source</th><th>Result</th></thead><tbody>';
for($i=0; $i < $max; $i++) {
   $s = isset($clean_s[$i]) ? $clean_s[$i] : '';
   $r = isset($clean_r[$i]) ? $clean_r[$i] : '';
   $table .= '<tr><td>'.$s.'</td><td>'.$r.'</td></tr>';
}

PHP 7 also can use syntax of $s = $clean_s[$i] ?? '';

If you are using php 7+

$max = max(array_map("count", [$clean_s, $clean_r]));
$table = '<table><thead><tr><th>Source</th><th>Result</th></thead><tbody>';
for($i=0; $i < $max; $i++) {
    $table .= "<tr><td>".($clean_s[$i] ?? "")."</td><td>".($clean_r[$i] ?? "")."</td><tr/>";
}

You can use the Null coalescing operator ?? operator for the same.

Note: The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.

EDIT:
Instead of writing a traditional snippet to get a bigger array,

$max = max(array_map("count", [$clean_s, $clean_r]));

This will give count of arrays passed and get max value out of it.

Demo .

Related