i have array value like this
Array (
[0] => A1
[1] => A2
)
Array (
[0] => B1
[1] => B2
[2] => B3
)
For exploding
$explodedeductedfinal = explode(",",$CODE);
this is my php code for outputting the data in td
foreach($explodedeductedfinal as $is){
$bankname = trim($is);
if (!empty($bankname)) {
echo "<td class='center'>$bankname</td>";
}else{
echo "<td class='center'>'novalue'</td>";
}
}
Output:
|Column A|Column B|Column C|
A1 A2
B1 B2 B3
Desired Output:
|Column A|Column B|Column C|
A1 A2 novalue
B1 B2 B3
i just want to output when the $bankname is empty it will show no value
The third element is not empty, it doesn't exist, so foreach
will only loop two. You might force it to the length you want and supply default values:
$default = array_fill(0, 3, 'novalue');
$explodedeductedfinal = array_replace($default, explode(",", $CODE));
foreach($explodedeductedfinal as $is){
$bankname = trim($is);
echo "<td class='center'>$bankname</td>";
}
well the foreach will go through every element of the array.
if (!empty($bankname)) {
Would not be empty since you are in a foreach. If there is always 3 columns, you could look into using a simple for statement, or alternatively, use javascript to fill in all empty cells in a table with a default value. for that, see this fiddle. I have had to use it in the past.
Calculate the maximum index of your arrays and loop on that instead of foreach. From a database, you could get the max number of values. Then use isset() to verify if the value is set for that index or not.
I coded this (quick and dirty, no database, no output formatting):
<table>
<?php
$arA = array(0 => 'A1', 1 => 'A2');
$arB = array(0 => 'B1', 1 => 'B2', 2 => 'B3');
function output_ar($ar,$maxindex)
{
for ($i = 0; $i <= $maxindex; $i++)
{
if (isset($ar[$i]))
{
echo "<td>" . $ar[$i] . "</td>";
}
else
{
echo "<td>novalue</td>";
}
}
}
$maxindex = max(count($arA),count($arB)) -1;
echo "<tr>
";
output_ar($arA,$maxindex);
echo "</tr>
<tr>
";
output_ar($arB,$maxindex);
echo "</tr>
";
?>
</table>