Code Snippets

Ajax requests with

This is one of the reasons I still like jQuery.

I’m sure all the new frameworks do similar stuff, but things like this are so simple with jQuery. Anyway, is a shorthand Ajax function. It’s the equivalent of doing this:

type: “POST”,
url: url,
data: data,
success: success,
dataType: dataType

So, with it, you can send an Ajax request this easily:

var posting = $.post(url, data);

Then, handle the response like this:

posting.done(function(data) {
// Handle data here

Or, all together like this:

$.post( “process.php”, function( data ) {
$( “.result” ).html( data );

It really is pretty simple.

Anyway, in my latest course I show you how to grab the form data from an HTML form, send it to a PHP script to be processed, generate a response in JSON and then handle that response in your jQuery to create an Ajax-powered quote request form on your website.

If you haven’t got into Ajax or jQuery, this is a good place to start because you get to see the whole request “loop” in a simple script that you can understand even if you’ve never done any of this before.

And, that’s along with learning about CSS Grid, CSS transitions, a little PHP and more.

Anyway, link to get no-cost access to the course here:



October 3, 2018

The One-Line Difference Between Ugly and Amazing Websites

Forget personal taste.

I’m telling you as sure as I’m sitting here… whatever your personal thoughts about the differences between this before and after… one will get you, “Um well… something just feels off.”

And, the other: “Wow! Clean, fresh. Amazing!”

It’s just how people are.

Anyway, here’s the before:

And, here’s the after:

This is a template I’m working on for a new course I’m doing. And, the difference is a single CSS declaration, but it’s light-years in terms of how it looks and how clients will react to it.

The code?

body, p, h1, h2, h3, h4, h5, h6 {
font-weight: 300;

Yup, that’s it.

Making the font-weight thin.

As I was building this, something just didn’t seem right. And, it was annoying the hell outta me. So, I started playing around with the fonts and voila… that was the trick. Suddenly, all was right in devtopia once again!

Of course, this won’t be the case in every situation.

Sometimes, thinning the text will make things worse.

It’s knowing when to and when not to.

That’s the difference between a gimmick or “hack”… and a fundamental.

And, it’s these subtle fundamentals that make all the difference.

I had a designer-friend of mine tell me that once.

It’s true.

And, it’s stacking up all these seemingly small things that makes the difference between a successful, celebrated and well-paid developer… and one who struggles, gets treated like dirt and has to scratch and claw for every penny.

Anyway, if you want to learn more stuff like this, check out my new HTML course. It’s all about the fundamentals and the simple stuff that makes a big impact. My guess is even if you’ve already learned some HTML…

You’ll find things you never knew…

That’ll make you a better developer.

Like Adolf Ezeribe, who just reviewed the course:

“An Excellent Refresher and HTML Primer for anyone.”

Anyhoo, up to you.

Link is here:



July 30, 2018

Send PHP Email Using PHPMailer

PHPMailer is a popular open source, email-sending library used by applications like WordPress, Drupal, SugarCRM, Joomla and others. This tutorial will show you how to install PHPMailer, set up SMTP and send email in PHP using PHPMailer. The source code is available to Patrons. Learn more about becoming a Patron and all the perks here:

April 30, 2018

How to Add Featured Images to Your WordPress RSS Feed

If you want to add featured images to your WordPress RSS feed (as enclosures), here’s what to do. First, you need to hook into the RSS feed as each item is built. This hook will do that:

add_action( ‘rss2_item’, ‘rss_add_featured_image’ );

Next, in our callback function, we need to check if the current post has a featured image. We’ll use has_post_thumbnail() for that:

if ( function_exists( ‘has_post_thumbnail’ ) && has_post_thumbnail( $post->ID ) ) {
// do stuff here

No, we need to get the URL of the featured image if it does exist. Here, we’ll need to run through a couple steps like this:

$attachment_id = get_post_thumbnail_id($post->ID);
$featured_image = wp_get_attachment_image_src( $attachment_id, ‘post-thumbnail’ );
$url = $featured_image[0];

Enclosures require you set not only the URL, but also the length of the file (in bytes) and the MIME type. Here’s how to do that:

$length = filesize(get_attached_file($attachment_id));
$type = get_post_mime_type($attachment_id);

And, finally, we can out put the enclosure using printf():

printf(‘<enclosure url=”%s” length=”%s” type=”%s” />’, $url, $length, $type);

This can all be inside a plugin or in your theme’s functions.php file. Although, I’d recommend using a plugin so if you change themes, you don’t have to transfers this code over to your new theme. And, if you’re ready to get serious about building WordPress plugins, then enroll in my WordPress plugin course. Inside, you build a contact form plugin, but, more importantly, you’ll learn fundamental WordPress plugin-building skills like creating custom post types, adding shortcodes, adding custom columns to the post table and more. You can learn more here.

April 24, 2018

PHP Add To and Remove Elements From an Array

In this tutorial, I’ll show you eight different ways to add to, remove from and insert elements to/from an array in PHP. PHP array functions used include: array(), array_push(), array_unshift(), array_pop(), array_shift(), array_slice(), count(), array_diff() and array_splice().

Let’s start with our original array:

// Our original array
$array = array(‘one’, ‘two’, ‘three’);

Here’s how you add elements to the end of a PHP array:

// Add elements to end of array
array_push($array, ‘four’, ‘five’);

Here’s how to elements to the beginning of a PHP array:

// Add elements to beginning of array
array_unshift($array, ‘zero’);

Here’s how to remove a single element from the end of an array:

// Remove one element from end of array

Here’s how to remove a single element from the beginning of an array:

// Remove one element from beginning of array

Here’s how to GET multiple elements from the end of an array:

// Get multiple elements from end of array
$lasttwo = array_slice($array, -2);

Here’s how to remove multiple elements from the end of an array and return what’s left:

// Remove multiple elements from end of array
$length = count($array);
$slice = array_slice($array, 0, $length-2);

Here’s how to remove specific elements (by value) from a PHP array:

// Remove specific elements from an array
$diff = array_diff($array, array(‘one’, ‘four’));

Here’s how to insert an element anywhere into an array:

// Insert element anywhere in array
array_splice( $array, 2, 0, ‘inserted’);

If you’d like to learn even more PHP, then consider taking my full PHP course here.

April 23, 2018

Static Methods and Properties In PHP

In my last tutorial, What Object-Oriented Programming Is NOT, I mentioned that over-using or mis-using the static keyword is one way developers get confused with object-oriented programming. That, often, they simply take their procedural code, dump into a class, make everything static and away we go.

That said, there CAN be legitimate uses for fully static classes.

I like the answer Pascal MARTIN gave on StackOverflow:

The distinction I make is this:

  • Use an instantiated class for actual objects in your applications (post, category, user, etc)
  • Use a static class for “libraries of code” that have useful functions

As Pascal said, that’s probably over-simplified, but it helps me keep my head straight. Of course, the question becomes… how do we write a static class.

The first thing to keep in mind is “once you go static, you can’t go back”… in a way. More specifically, you can’t use object properties or methods in static methods. So, this won’t work:

class Library {
public $var = ‘Hey’;

public static function do_stuff() {
echo $this->var;

Library::do_stuff(); // Triggers: Fatal error: Using $this when not in object context

That’s because $this references and instantiated object. But, we bypass that when using static methods. So, $this essentially doesn’t “exist”. But, you might think you could do this:

class Library {
public $var = ‘Hey’;

public static function do_stuff() {
echo Library::$var;

Library::do_stuff(); // Triggers: Fatal error: Access to undeclared static property: Library::$var

So, once you declare a method static… basically everything it touches has to be static, too. Thus, this is what works:

class Library {
public static $var = ‘Hey’;

public static function do_stuff() {
echo Library::$var;

Library::do_stuff(); // Outputs “Hey”

One way you might use this, then, is something like this:

class Library {
public static $date_format = ‘F jS, Y’;

public static function format_date($unix_timestamp) {
return date(self::$date_format, $unix_timestamp);

echo Library::format_date(time()); // Outputs formatted date

The format_date() method is one that could be used in various places throughout your application and wouldn’t need constantly re-instantiated to use. And, of course, this Library class could contain various, similar methods that have data-agnostic uses. A kind of “catch-all” for miscellaneous functions.

And, of course, as you’ve seen the way to make a property or method static is to simply add the “static” keyword to the declaration, like so:

class Library {
public static $var = ‘Hey’;

public static function do_stuff() {
// do stuff

So, there you go. Now, if you want to keep going and learn how to build professional PHP applications using object-oriented programming, then check out my full object-oriented programming course here (also available on Udemy here).

January 2, 2018

What object-oriented programming is NOT

I’ve made this argument several times, but object-oriented programming is MORE (much more) than knowing how to write a class. It’s a “paradigm” (as WikiPedia calls it) or a “model” (that’s Tech Target’s word). I call it an “approach”… but it’s an approach to application-building.

OOP is not about how you write your code… it’s about how you build your applications. That may not make sense, at first… but it is an important distinction. So, let’s look at some code and see if we can make this clear.

So, the first thing object-oriented programming is not is…

Object-Oriented Programming Is Not Writing a Class

You use classes, but that’s not what it IS. A lot of times what I see developers do is take a set of functions like this:

function my_func_one() {
// do stuff

function my_func_two() {
// do stuff

And, just do this with it:

class MyClass {
function my_func_one() {
// do stuff

function my_func_two() {
// do stuff

That’s not object-oriented programming… that’s namespacing. Which is fine, but you’d be better off just using actual namespaces like this:

namespace App\Functions;

function my_func_one() {
// do stuff

function my_func_two() {
// do stuff

// Note: prior to PHP 5.6 this wouldn’t work because importing function and
// constant names wasn’t supported. 5.6+ DOES support this.

It’s simpler syntax, it’s easier to update your existing procedural code and you’d being using the “right tool for the right job” in my opinion.

Object-Oriented Programming Is NOT Static

Another one I see is heavy use of the “static” keyword. So something like this:

class MyClass {
public static function my_func_one() {
// do stuff
public static function my_func_two() {
// do stuff


This is really the same mistake as before, just more fancy-looking. The reason you’d do this is to put your functions into a class and be able to call them in the procedural way you’re used to… but not have to “mess with all that instantiating nonsense”. This, again, is really just namespacing. (There are proper uses of “static” in OOP, but they’re fairly rare. So, if all or most of your class methods are static… that’s not object-oriented programming.)

Object-Oriented Programming Is NOT MVC

This will ruffle a few feathers probably, but OOP and MVC are, in fact, two different things. OOP is an “approach” (model, paradigm) to application-building. MVC is one, of many, application design patterns that employ OOP principles. So, you can “do OOP” without MVC.

I bring this up because MVC’s popularity (for good reason) tends to make people think that’s all there is. “If I’m gonna OOP, I gotta MVC.” But, there are plenty of other patterns out there… some of which I personally prefer to MVC.

That’s why in my object-oriented programming course, I show you MVC, but I also show you another design pattern… one I personally like better. To challenge you to think about it different ways and develop what works for you… not just follow what everyone else is doing.

That and a lot of the frameworks that employ MVC principles actually use a distorted form of it… but that’s a topic for another time.

What Object-Oriented Programming IS

I’ll re-iterate… it’s an entire “re-thinking” of how you build your applications. Procedural coding tends to focus on process over data. We think of what we need to DO first. We need to process this form data or edit this blog post. And, those processes tend to be what drives our application design decisions.

OOP is different. It focuses on the data first. Instead of breaking your applications down into processes, you break into down into objects. And, objects here is used in the general sense… a phone is an object, a remote is an object… these things are literal objects in the real world.

So, we build our applications in the same way we view the world in real life. We break a CMS down by “post”, “category”, “tag”, “author”, “comment”… and we think about our data model FIRST. Then, we write the code to create, read, update and delete.

It’s Not Your Fault

Now, I know you might feel like I’m ragging on you if you’ve done any of this stuff. I’m not. I did all the same stuff. Probably anyone who’s made the switch from procedural to object-oriented programming did this same stuff.

I think most coders’ minds are naturally oriented to think in processes. So, breaking out of that is difficult. But, ultimately, for large, complex applications OOP is a better way to build. It’s easier to think about your application mentally in this way. Your code is often more organized. And, it’s more in line with how your end-user sees your application.

If you’d like to dive into all this more, then check out my object-oriented programming course. I’ll clear up all the confusion you might have surrounding OOP and show you how to build professional PHP applications using object-oriented programming.

December 22, 2017

Inheritance In a PHP Class and Object-Oriented Programming

Let’s talk about inheritance in PHP. First, here’s how you do it:

class Daddy {
public function my_method() {
echo “I’m the parent”;

class Son extends Daddy {


$child = new Son;
$child->my_method(); // This outputs “I’m the parent” from the parent class

The child is the class DOING the extending. The parent is the class BEING extended. And, the child inherits any public or protected properties and methods from the parent. This is why “Son” has no methods, but still outputs the results of my_method(). Because it inherited that method from Daddy.

But, private methods and properties are NOT inherited. So, this won’t work:

class Daddy {
public function my_method() {
echo “I’m the parent”;

private function you_cant_haz() {
echo “Only Daddy gets me!”;

class Son extends Daddy {


$child = new Son;
$child->you_cant_haz(); // This triggers a fatal error

You can also override inherited methods in the child. Like this:

class Daddy {
public $var = “Call me Daddy! “;

public function my_method() {
echo $this->var;

private function you_cant_haz() {
echo “Only Daddy gets me!”;

class Son extends Daddy {
public $var = “Uh, that’s creepy. No!”;

public function my_method() {
echo $this->var;

$parent = new Daddy;
$parent->my_method(); // This outputs “Call me Daddy!”

$child = new Son;
$child->my_method(); // This outputs “Uh, that’s creepy. No!”

One example use case for this is WordPress widgets. When creating a new widget, your individual widget class extends WP_Widget to access and override its default methods. WordPress then does the “magic” of putting your widget together simply by you overriding the WP_Widget methods in your class.

Another example is the example OOP application shell I show you how to build in my object-oriented programming course. I give you a primer on MVC, which is obviously super popular right now, but is only one among many design patterns. But, I also show you another pattern I learned a few years back that I personally like better… and it involves some strategic inheritance like this. You can learn more about and enroll in my object-oriented programming course here.

December 21, 2017

How to Validate (and Sanitize) User Input In PHP Using Filter_Input() and Filter_Var()

Never trust user data.

That’s the mantra. Good advice. So, how do you do it? In recording my newest training course, How to Submit and HTML Form to MySQL Using PHP, I talk quite a bit about the concept of “layered security”. Not my idea, though… it’s a pretty standard and accepted concept in application security (WikiPedia article on it here).

So, you have:

  • Prepared statements to stop SQL injection
  • Output escaping for XSS attacks
  • Tokens for CSRF

And, one I don’t see as much: input validation and sanitization using PHP’s filter_input() and filter_var() functions. So, you can do something like this:

<?php $name = filter_var($_POST[‘name’], FILTER_SANITIZE_STRING); ?>

That runs the $_POST element “name” through FILTER_SANITIZE_STRING… which “Strip tags, optionally strip or encode special characters.” You can see a full list of available filters here.

You can also validate like this:

<?php $email = filter_var($_POST[’email’], FILTER_VALIDATE_EMAIL); ?>

Which will: “Validates whether the value is a valid e-mail address.” If it’s not a valid email address, filter_var() returns false meaning you can run validations checks off it, like this:

$email = filter_var($_POST[’email’], FILTER_VALIDATE_EMAIL);

if ( $email === false ) {
// Handle invalid emails here

Optionally, you can use filter_input() like this:

$name = filter_input(INPUT_POST, “name”, FILTER_SANITIZE_STRING);
$email= filter_input(INPUT_POST, “email”, FILTER_VALIDATE_EMAIL);
$search = filter_input(INPUT_GET, “s”, FILTER_SANITIZE_STRING);

And, so on.

You also have filter_var_array() and filter_input_array() for filtering entire arrays at once WITH unique flags for each element.

In any case, do this to add just one more layer of security and ensure the user input you accept into your application isn’t going to let a hacker in the front door.

Also, if you’d like to learn preventing SQL injection and XSS attacks, as well, enroll in my new course. We go into all of it along with creating an HTML5 form, a MySQL database and tying the two together with PHP — in video format so you can see it come together. Plus, you get access to final source code to download and use as you wish.

December 1, 2017

Output the last row inserted in MySQLi

MySQLi makes grabbing the last inserted row easy. After running your insert query, you can do this:

$id = $mysqli->insert_id;

Then, you can query for that row like this:

$result = $mysqli->query(“SELECT * FROM table_name WHERE ID = {$id}”);

And, fetch the result as an object:

$user = $result->fetch_object();

From there it’s a simple echo to output it to your page:

echo $user->user_name;

(Although, you’ll want to use htmlspecialchars or htmlentities to escape the output and prevent XSS attacks. But, we’ll save that for another day.)


Anyway, in the newly released Module 3 of PHP 101, I show you how to build a fully-functioning PHP form that submits and retrieves data from your database… so you’ll learn how to do this with all the bells and whistles like prepared statements, input filtering, output escaping and more.

It’s a simple proposition…

If you want to master all the ins and outs of MySQL…

This is how you do it.

Right now, you can grab all three modules for just 27 buqs.

That’s 10 buqs off the regular.

Here’s the link



February 21, 2017

Connecting to MySQL with PDO

With MySQLi, it looks like this:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

But, PDO is a bit different because it can interact 12 different types of databases: Oracle, PostgreSQL, SQLite, MySQL, Cubrid and several others. So, when using it you have to specify which driver you want to use.

Like this:

$conn = new PDO(“mysql:host={$db_host};dbname={$db_name}”, $db_user, $db_pass);

Notice the “mysql:host=” bit.

For different drivers, you just change out the “mysql” part.

So, PostgreSQL would be:

$conn = new PDO(“pgsql:host={$db_host};dbname={$db_name}”, $db_user, $db_pass);

For Oracle, it’d be:

$conn = new PDO(“oci:host={$db_host};dbname={$db_name}”, $db_user, $db_pass);

And, so on.

Nice thing is…

The code after this doesn’t change for each kind of database. So, you could write the rest of your database interaction code initially for MySQL… then, change to say PostgreSQL.. .and all you have to do is change out the drive designation (mysql, pgsql, oci, etco).

That’s why you hear people recommending you use PDO a lot.

If there’s any chance you might switch to a different database…

It makes sense.

Anyway, this one of the many things you’ll learn inside Module 3 of PHP 101 (which I just uploaded to the site). Along with the basics of CRUD, you’ll learn MySQLi and PDO, prepared statements, building a database class, submitting an HTML for to your database (AND getting data back from it)… and more.

Right now, you can grab all 3 modules for just 27 buqs.

That’s 10 buqs off the regular fee.

Use this link to get it:



February 16, 2017

Simple input filtering in PHP

Here’s one I don’t see talked about much:

$name = filter_input(INPUT_POST, ‘name’, FILTER_SANITIZE_STRING);

What this does is grab the “name” element from your POST array and run it through the the filter: FILTER_SANITIZE_STRING… which removes all HTML tags from the string (since we know a person’s name doesn’t have HTML in it).

It’s a really simple way of quickly filtering your data.

Here’s another:

if ( ! $email = filter_input( INPUT_POST, ’email’, FILTER_VALIDATE_EMAIL ) ) {
die(‘Invalid email’);

This one validates the submitted email address.

And, returns false if it’s invalid.

Again, a very simple way of quickly validating your data.

And, there’s a roughly 20-30 different filters you can run your data through. Things like: FILTER_VALIDATE_URL, FILTER_VALIDATE_INT, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_EMAIL and more.

The idea here is:

  1. Filter data like this on input
  2. Escape it on submission to MySQL
  3. Escape it on output to the browser

That little routine will help you prevent invalid data, SQL injection, XSS attacks and whole host of other problems.

Anyway, it’s one of the things I show you in Module 3 of PHP 101. Along with, of course: CRUD basics, PDO, MySQLi, Prepared Statements… plus building a database class AND submitting HTML form data to MySQL using all of this.

Use this link to get the details on the course and grab Modules 1-3:



February 10, 2017

Prevent SQL injection attacks with prepared statements

Bit of a hot topic lately in my inbox.

Here’s what an old, vulnerable query might look like:

$expected_data = 1;
$query = “SELECT * FROM users where id=$expected_data”;
$result = $mysqli->query($query);

The problem here is we’re injecting user-submitted data directly into our SQL statement without any sort of escaping or validation. So, a hacker could enter something like this in our form:

1; DROP TABLE users;

Changing our full query to:

SELECT * FROM users where id=1; DROP TABLE users;

Which, as you can probably see, will execute the SELECT statement but then drop our users table. No bueno. And, that’s a simple example. SQL injection attacks can be used to do all sorts of things: getting passwords, gaining privileges, making superusers… and all sorts of stuff.

Luckily, there’s an easy way to prevent this class of SQL injection:

Prepared statements.

Prepared statements split the query from the data so that the data submitted can’t be used to alter how the query is run; thus preventing injection attacks. Here’s an example of how our code would change:

$expected_data = 1;
$stmt = $mysqli->prepare(“SELECT * FROM users where id=?”);
$stmt->bind_param(“d”, $expected_data);
$result = $stmt->get_result();

Notice how we separated the data from the query. We send the query to the server first and then we bind the data to that. This prevents the submitted data from altering the query and letting the hacker in.

This is how you should write your queries.

Now, if this stuff is new to you or you don’t feel like you quite fully get it yet, then I recommend diving into it. One good way to learn everything PHP is with this tutorial. You’ll learn prepared statements… but also OOP, all of MySQL with PHP, $_GET, $_POST, working with files, folders, if/else/switch… all of it. Plus, you build several fully-functioning scripts so you learn how to put it all together and build something real.

No brainer, IMNSHO:


John “Don’t Hack Me Bro” Morris

January 29, 2017

How to Create Tweets Using the Twitter API

I’m going to quickly show you the exact code to send a tweet using the Twitter API. Then, how to learn to build a full-fledged Twitter app.

Let’s dig in.

Before you start, you need three things:

  1. A developer account on Twitter. (
  2. A Twitter app for the API keys and access tokens (
  3. The Twitter OAuth PHP class (

Download the class to your working folder. Then, create a file called index.php (or whatever you want) and include the Twitter OAuth class like so:

require “twitteroauth/autoload.php”;
use Abraham\TwitterOAuth\TwitterOAuth;

Next, we need to connect to the API:

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
$content = $connection->get(“account/verify_credentials”);

You, of course, need to change out CONSUMER_KEY, CONSUMER_SECRET, $access_token and $access_token_secret with the actual ones from your Twitter app (which is why you need to create one to do this).

Then to get tweets, do this:

$statuses = $connection->get(“statuses/home_timeline”, [“count” => 25, “exclude_replies” => true]);

This will get your last 25 tweets, excluding replies.

Finally, to create a new tweet, do this:

$statues = $connection->post(“statuses/update”, [“status” => “hello world”]);

Changing “hello world” to whatever you want to tweet.

That’s it. Pretty damn easy.

Now, if you’d like to see all of this in a video walk-through and learn how to build a full-fledged Twitter client, then grab a copy of the Complete Web Developer Course by Rob Percival 75% off the normal fee here.

In the API section, he covers all of this… plus a Google Maps client… and you’ll build 25 websites and mobile apps throughout the course.

No way you go through this and aren’t ready to take on a full-time IT job.

Anyway, go here to learn all this at 75% off the normal cost:

December 13, 2016

PHP cURL Tutorial and Example

A simple PHP cURL tutorial and example. Learn how to use curl_init, curl_setopt, and curl_execute. Also learn how to POST data to a remote URL using cURL.

Ready to learn even more PHP? Take my free Beginner’s Guide to PHP video series at

Get this source code along with 1000s of other lines of code (including for a CMS, Social Network and more) as a supporting listener of the show at

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source code and exclusive courses on Patreon.

August 16, 2016

PHP 7’s Null Coalescing Operator: How and Why You Should Use It

PHP 7’s null coalescing operator is handy shortcut along the lines of the ternary operator. Here’s what it is, how to use it and why:

Ready to learn even more PHP? Take my free Beginner’s Guide to PHP video series at

Get this source code along with 1000s of other lines of code (including for a CMS, Social Network and more) as a supporting listener of the show at

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source code and exclusive courses on Patreon.

August 2, 2016

The Thing About PHP 7’s Spaceship Operator

Subscribe So You Never Miss An Episode


May the force be with you… 😉

Unless you’ve been under a rock (which is totally cool if so) you know PHP 7 has been out for a bit now. I finally took some time the other day to fire it up on one of my dev servers and see what all the fuss is about.

Online, I’d kept hearing about this “spaceship” operator.

This thing’s kind of cool actually. Let me show you.

So, here’s a common bit of code you might see pre-PHP7:


This is a sorting routine.

usort() lets you sort an array using a user-defined comparison function… in this case compare_length(). So, what this does is re-arrange the $names array to be in order of the length of the names in it. Here’s the output:


Ok, simple enough.

But, notice the big compare_length() function. It works fine, but that’s a good chunk of code just to run a simple comparison. And, this is where the spaceship operator comes in. Here’s what the function looks like with PHP 7:


Just three lines now. Pretty sweet!

So, how does the spaceship operator (<=>) work?

You can use it just like you might any other operator. For example, equals:

1 == 1;

Except it looks like this in spaceship mode:

1 <=> 1;

When you do that, PHP will run a “trinary” comparison. So, it’ll check to see if 1 is less than, equal to or greater than 1. Thus the syntax of a less than sign (<), an equal sign (=) and a greater than sign (>): <=>.

And here’s what it’ll return…

If $a is less than $b, it returns -1. If $a is equal to $b, it returns 0. And, if $a is greater than $b, it returns 1. Here’s an example:


Slicky ricky, eh?

Anyhoo, thought I’d give you the low down on it. You’re welcome! 😉

If you want to learn even more PHP so you can still cram your skull with Cheetos and binge watch Star Wars movies without having to deal with that annoying boss, then get your butt over to: and take my free PHP course.

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source code and exclusive courses on Patreon.

July 22, 2016

TUTORIAL: How to Build an Advanced Website Template Using PHP and Bootstrap

INSPINIA has sold 29,598 units at $18 a piece. That’s $532,764.

SmartAdmin sold 20,136 units at $12 a piece. That’s $241,632.

Unify… $321,828.

That’s just three of over 800 Bootstrap templates on WrapBootstrap. And that’s just one Bootstrap marketplace. Obviously, people want these things.

But, they all have a major problem. One that makes it hard for clients to actually implement on their site, makes updates horrifying and ensures after-launch tweaks are a nightmare.

I’ll show you how to fix that problem and turn these basic template into advanced “site-builders” using a little PHP magic.

You think maybe you could make a few bucks doing this for clients? Uh yeah… Watch:

Get the source code as a supporting listener on Patreon.

Subscribe to the Podcast


P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, source code and exclusive courses on Patreon.

June 29, 2016