We have a requirement to fetch data from database and display user names and their salaries.
Output required:
Morgan's salary: 6000, Jermy's salary: 5500, Phil's salary: 5500, Anthony's salary: 5500, John's salary: 5500, Norman's salary: 5500
There are 2 ways of doing this that generate the same result.
<?php
$databseArray = [];
$databseArray[] = [1, 'Morgan', 6000];
$databseArray[] = [2, 'Jermy', 5500];
$databseArray[] = [3, 'Phil', 5500];
$databseArray[] = [4, 'Anthony', 5500];
$databseArray[] = [5, 'John', 5500];
$databseArray[] = [6, 'Norman', 5500];
echo 'Approach 1';
echo '<br/>';
if (! empty($databseArray)) {
$str = '';
$cntr = 0;
$len = count($databseArray);
foreach ($databseArray as $databseRow) {
$str .= ' '.$databseRow[1] ."'s". ' salary: '.$databseRow[2];
if ($cntr < ($len-1))
$str .= ', ';
++$cntr;
}
}
echo $str;
echo '<br/>--------------------------------------------------------------<br/>';
echo 'Approach 2';
echo '<br/>';
$outputArr = [];
if (! empty($databseArray)) {
foreach ($databseArray as $databseRow) {
$outputArr[] = ' '.$databseRow[1] ."'s". ' salary: '.$databseRow[2];
}
}
echo implode(', ', $outputArr);