I've been helping out of couple of friends with their University assignments recently and one thing that has bugged me to no end, is how they're not being shown how to keep code clean and manageable.

Take the following example (which is close to what their University lecture's have been giving out as an example).

<?php
	$fruitArray	= array(
					"apple" => "green",
					"tomato" => "red", 
					"banana" => "yellow", 
					"grape" => "purple", 
					"orange" => "orange");
	
	echo "<table>";
	echo "<tr>";
	echo "<th>Fruit</th>";
	echo "<th>Colour</th>";
	echo "</tr>";
	ksort($fruitArray);
	foreach ($fruitArray as $fruit => $colour) {
		echo "<tr>";
		echo "<td>" . $fruit . "</td>";
		echo "<td>" . $colour . "</td>";
		echo "</tr>";
	}
	echo "</table>";
?>

Without going into too much detail, it's generally a terrible idea to be echo-ing HTML code in this way. More pressing than just losing HTML syntax highlighting in your preferred editor, keep track of tabulation in your HTML code is now non existent, although you could add tabs within the quotes - it's simply going to end up far more messy than before. You've also lost your line-breaks between elements. Not a huge issue, but when you start to view the source of your page for debugging purposes - everything is going to be spit out on one long line. Again, you can counter this by adding "\n" to the end of your strings - but we're slowly getting out of control for some basic code management.

It's my opinion, that you should firstly keep your logic well separated from your HTML. In this example, array sorting should be done before you start print HTML. You should learn the alternative syntax structure for 'if', 'foreach' and 'while' statements.

Where possible (server allowing, and you can add your own .htaccess file if your university has turned off most things) - use shortform PHP statements. That is, instead of <?php echo $title; ?>, try using the much smaller <?=$title;?>

Let's try again.

<?php
	$fruitArray	= array(
					"apple" => "green", 
					"tomato" => "red", 
					"banana" => "yellow", 
					"grape" => "purple", 
					"orange" => "orange");
	ksort($fruitArray);
	
	// Any other form of math or logic to go here.
?>

<!-- From this point onwards, we're mostly HTML now -->
<table>
	<tr>
		<th>Fruit</th>
		<th>Colour</th>
	</tr>
	<?foreach ($fruitArray as $fruit => $color):?>
	<tr>
		<td><?=$fruit;?></td>
		<td><?=$color;?></td>
	</tr>
	<?endforeach;?>
</table>

Already we've made this much easier to manage because our logic is quite seperate from the HTML we're displaying. We're still able to do loops using the alternative syntax mentioned earlier which allows us to use foreach(): and endforeach; rather than keeping track of opening and closing brackets.

And if you don't have PHP short tags enabled on your server (yes you James), ensure you replace '<?=' with '<?php echo '. But that will still keep your code extremely clean and manageable.