PHP Don’t Abbreviate

Simply put, please do not abbreviate in your code.

Always code as if the guy who ends up maintaining your code will be a
violent psychopath who knows where you live.  Code for readability. John F Wood

If others have to read it they will have no idea what an abbreviation means and when you come back to it in 6 months time will you remember what this does?

<?php
function delHisFile($p) { 
// Do something
 }

Or

function sort(array $a) {
 for ($i = 0, $c = count($a);  $i < $c;  $i++) { 
// Do something
 }
}

How does this read?

<?php
function deleteHistoryFiles($path) { 
// Do something
 }


function sort(array $array) {
 for ($index = 0, $array_count = count($array); $index < $array_count;  $index++) { 
// Do something
 }
}

When I started out coding for some reason I thought variables, functions, methods and class names that where long and descriptive would have an adverse effect on performance ( I know daft eh) .

PHP foreach() function

Okay, another everyday snippet of PHP code tweaked.

We all use the following

<?php

foreach($array as $item){

// Do something

}

?>

Which works fine, sometimes the // Do something gets complicated with HTML

<?php

foreach($array as $item){

echo '<tr>';

echo '<td>'.$item->first_name.'</td>';

echo '<td>'.$item->last_name.'</td>';

echo '<td><a href="'. $item->name .'">'.$item->email.'</a></td>';

echo '</tr>';

}

?>

After a while it gets messy and can be easy to have errors in your HTML which your editor might not pick up.

How about this for a solution – its an Alternative Form

<?php

foreach($array as $item) : ?>

<tr>

<td><?= $item->first_name ?></td>

<td><?= $item->last_name ?></td>

<td><a href="<?= $item->email ?>"><?= $item->email ?></a></td>

</tr>

<?php endforeach ?>

There are a few other ways but this reads really well. If you are looking to store the HTML as a variable before echoing it out have a look at ob_start(). However, creating chunks of HTML and passing them from place to another isn’t really good form – see separations of concerns  and MVC

 

This also works for if() statments