How to Write Better PHP: An Ultimate List of Tips for PHP Beginners

If you are trying to get better at PHP, here are over 100 great tips and tricks to improve

By: Ajdin Imsirovic 06 April 2019

To get better at coding, you often need to get out of your comfort zone. Sometimes that doesn’t have to be such a hard thing to do.

It is often enough to just get a new piece of information regarding some simple concept in a programming language.

In this article, we’ll look at over 100 gotchas in PHP.

1. You can embed HTML in PHP conditionals

You can mix HTML and PHP in many different ways. Here’s an example of adding HTML directly to PHP conditionals:

<?php if ($gold = 0) { ?>
  <p>You are out of gold.</p>
<?php> } elseif ($gold >= 1 && $gold < 100) { ?>
  <p>You are running out of gold.</p>
<?php> else { ?>
  <p>You have enough gold. Go to the market and buy an improvement.</p>
<?php> } ?>

As can be seen in the code above, sometimes we don’t have to use the echo language construct at all!

2. Falsy values in PHP

Here is a list of falsy values in PHP:

  • The keywords FALSE and NULL
  • Zero (0, 0.0, ‘0’, “0”)
  • An empty string (‘’,””)
  • An array with zero elements (contrary to JS!)
  • A SimpleXML object created from empty tags

All the above values are falsy in PHP. Everything else is true.

The following values are always true:

  • -1
  • ‘false’
  • ‘null’

3. Four ways to create an array in PHP

There are several ways to create and update arrays in PHP:

$arr = array('zero','one','two','three','four');
$arr2 = ['zero','one','two','three','four'];
$arr[] = 'zero';
$arr2[] = 'zero';

4. Adding months to the alt attribute of the img HTML element with PHP

$monthnumber = date('n');
$specials_alt = array(
    'January special: Cacti galore,
    'February special: Flowers and hearts for Valentines',
    'March special: Bright red camellias',
    'April special: Fresh tulips',
    'May special: Purple iris',
    'June special: Beautiful bougainvillea',
    'July special: Stunning white hydrangeas',
    'August special: Subflowers',
    'September special: Pink crysanthemums',
    'October special: Purple orchids',
    'November special: Bonsai with rock',
    'December special: Dried flowers for decoration'
);
print_r($specials_alt);
<?php echo $specials_alt[$monthnumber -1]; ?>

5. Echoing a PHP array to a web page as an unordered list

Unlike JS, arrays in PHP are not converted to strings automatically. To do that, you need to use the implode function.

<?php $colors = ['red','orange','yellow','green']; ?>
<ul><li><?php echo implode('</li><li>', $colors); ?></li></ul>

Even better way to do this is using a loop:

<ul>
<?php
foreach($colors as $color){
  echo '<li>' . $color . '</li>';
}
?>
</ul>

What’s the difference between using implode or a loop? With implode you can only specify a separator, but in a loop, you can add any additional code you like. For example:

<?php
foreach ($colors as $color) {
  if ($color == "orange"){
    continue;
  }
  echo '<li>' . ucfirst($color) . '</li>';
  if ($color == "blue"){
    break;
  }
}
?>

6. You can’t use an associative array variable in a double-quoted string

Let’s say we have an associative array like this:

<?php
  $cars = [
  'fastest' => 'Ferrari',
  'comfortable' => 'Lincoln',
  'tiny' => 'Smart',
  'tough' => 'Ford F150'
];
?>

Let’s also say we want to echo out a member of this associative array, with the following code:

<?php echo "The fastest car in the list is $cars['fastest']"; ?>

Doing this would throw an error. So how do we fix it? We need to re-write our code like this:

<?php echo "The fastest car in the list is {$cars['fastest']}"; ?>

7. Use in_array to find array elements easily

<?php
$cars = ['vw', 'bmw', 'skoda', 'fiat', 'opel', 'audi'];
$order = 'audi';
if (in_array($order, $cars)) {
  echo "<p>Yes, $order are in stock.</p>";
}else{
  echo "<p>Sorry, no $order available.</p>";
}
?>

Alternatively, you could use the following code:

if (in_array($needle, $haystack)) { //... }

8. Iterating over sub-arrays

Let’s say we have the following images:

  • feature_spring.jpg
  • feature_summer.jpg
  • feature_autumn.jpg
  • feature_winter.jpg

Let’s also say that we need to show different images based on the month of the year. So if months are Dec, Jan, or Feb, we’ll show the feature_winter.jpg image.

Here’s how we’d do it:

$features = array(
  'winter' => 'Beautiful arrangements for any occasion.',
  'spring' => 'It must be spring! Delicate daffodils have arrived.',
  'summer' => "It's summer, and we're in the pink!",
  'autumn' => "Summer's over, but our flowers are still a riot of colors."
  );
$seasons = array(
  'winter' => array('dec', 'jan', 'feb'),
  'spring' => array('mar', 'apr', 'may'),
  'summer' => array('jun', 'jul', 'aug'),
  'autumn' => array('sep', 'oct', 'nov')
  );

The features array contains headlines for each season. What we need to do is find the current season so we can display the current tagline and the correct image. That’s what the $seasons array is for. Each array key has the name of the season, by the value is another array. And this is what’s known as a multidimensional array. It’s an array of arrays. Just think of it as 4 arrays, but instead of each of them stored in a variable, it’s identified by a string. So we have an array for winter, another for spring, and so on. Each array consists of the first three letters of a month in that season. To get the first three letters of the current month, and to convert the entire result to lowercase, we use this syntax:

$monthname = date('M');
$monthname = strtolower($monthname);

So now we can use $monthname to loop over these arrays:

foreach ($seasons as $key => $montharray) { // $montharray could be, e.g 'dec', 'jan', 'feb'
  if (in_array($monthname, $montharray)) {
    $season = $key;
    break;
  }
}

Now we can simply echo out the tagline in our HTML:

<p class="overlay large"><?php echo $features[$season]; ?></p>
<img src="images/feature_<?php echo $season; ?>.jpg" alt="White Rose Arrangement">

9. Gathering Form Input: POST

Here’s a form in HTML:

<!-- the opening <form> tag doesn't have an action attribute, -->
<!-- which means the form will simply reload when the submit button is pressed -->
<!-- so we'll use that to inspect the data that is sent by the form -->
<!-- when the server receives a request for the page, php automatically creates an array called $_POST -->
<!-- that contains any data submitted to the page by the post method -->
<!-- it's an associative array that uses the NAME attributes of the form's input elements as the array keys -->
<form method="post">
  <p>
    <label for="textfield">Text Field:</label>
    <input type="text" name="textfield" id="textfield">
  </p>
  <p>
    <label for="quantity">Number:</label>
    <input name="quantity" type="number" id="quantity" min="0" value="0">
  </p>
  <p>
    <label for="color">Color:</label>
    <select name="color" id="color">
      <option value="yellow" selected>Yellow</option>
      <option value="red">Red</option>
      <option value="green">Green</option>
      <option value="orange">Orange</option>
    </select>
  </p>
  <p>
    <!-- the name of the submit button is "order" -->
    <!-- you can use that as the condition to test whether the form has been submitted -->
    <!-- because $_POST['order'] will only exist if the form has been submitted -->
    <input type="submit" name="order" id="order" value="Order">
    <input type="hidden" name="price" id="price" value="3">
  </p>
</form>
<pre>
<?php
if (isset($_POST('order'))) {
  print_r($_POST);
}
/*
The above PHP will produce:
Array
(
  [textfield] => David
  [quantity] => 3
  [color] => red
  [order] => Order
  [price] => 3
)
*/
?>
</pre>

10. How is the query string created in the browser?

When the method for a form is “get”.

Feel free to check out my work here: