welcome to StackOverflow. Majed's answer is correct, and should probably be marked as the accepted answer. I'd recommend a few other changes though.
- Separation of Concern: Fewer lines of code does not necessarily mean it's simpler or easier to maintain. Bite-sized chunks, and fewer decision branches therein, does. In its most basic form this principle dictates that you not mix your algorithm logic with your presentation logic.
view.php
<style>
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
</style>
<body>
<table style="border: 1">
<tr>
<th>i</th>
<th>square</th>
<th>cube</th>
</tr>
<?php
foreach ($powers as $index => $power) {
echo "<tr><td>$index</td>";
foreach ($power as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
?>
</table>
</body>
exponentHelpers.php
function square($x)
{
return $x * $x ;
}
function cube($y)
{
return $y * $y * $y ;
}
controller.php
require_once "exponentHelpers.php";
$base = 10;
$powers = [];
while($base--) { //Note, the self-decrementing short-hand will result in the values listed in reverse order.
//You could write it long-hand if you prefer, or call array_reverse() afterwards.
$powers[] = [
square($base),
cube($base),
];
}
require_once "view.php";
- PSR2: Never too soon to learn good habits. PSR2 basically describes an industry-standard of formatting your code to keep it looking consistent and easy to read regardless who wrote it. You have a couple violations there.
- Tabs should be 4 spaces, not 5.
- Opening brackets for functions should be on a new line.
- Avoid single-line control structures. i.e, use brackets for loops and if-statements:
for ($i=1; $i <= 10 ; $i++) {
echo "
<tr>
<td>$i</td>
<td>".square($i)."</td>
<td>".cube($i)."</td>
</tr>";
}
Power function: You kind of reinvented the wheel with your square()
and cube()
functions. Php provides a pow($base, $exponent)
function that does the same thing, and isn't limited to one power. So this could do away the exponentHelpers.php
section altogether.
PSR2-compliant shorthand: Entirely your preference if you want to use this, but there are two bits of Php you might be intersted in here, looking at the loops in the view.php
section. One is array_map()
, which allows for imperative array looping and result retrieval on the same line. The other is <?=
, which is HTML-template shorthand for <?php echo ...
. Put them together, and you could present your loops more succinctly:
<?= array_map(function (array $power, $index) {
//Newlines are optional. Just makes the output a little easier to read.
$powerElms = preg_replace("/^.*$/", "<td>$0</td>", $power);
return "<tr>\n<td>$index</td>\n" . implode("\n", $powerElms) . "</tr>\n";
}, $powers, array_keys($powers)) //Missing semicolon is not a typo. It's not needed with this syntax. ?>