Type casting in PHP

Let’s say we didn’t like how PHP assigned a string for the title and an integer for number of posts (even though that’s exactly what we wanted — just follow along for a moment).

We’re able to “cast” variables as different types at the time of creation. This forces these types to be the exact type that we specify.

We can do this by adding parentheses before our variable assignment, and then specifying the type we wish to cast this variable to.

<?php
$title = (integer) 'My Blog';
$numPosts = 10;
?>
<h1><?= $title ?></h1>
<p><?= gettype($title) ?></p>
<h2><?= $numPosts ?></h2>
<p><?= gettype($numPosts) ?></p>

Let’s cast the title to an integer. If we save and refresh the page, we’ll see something funky happened!

PHP took our string, and since it was cast as an int, converted that string to the closest representation of it that it could, which here, is a zero. We will noticed that the call to gettype also changed to confirm that this variable is now an integer.

Let’s do the same to numPosts, but make it a string, and refresh:

<?php
$title = (integer) 'My Blog';
$numPosts = (string) 10;
?>
<h1><?= $title ?></h1>
<p><?= gettype($title) ?></p>
<h2><?= $numPosts ?></h2>
<p><?= gettype($numPosts) ?></p>

This time, the only thing that changed is the data type. That is because PHP basically just wraps our integer in quotes. This is also what PhpStorm is saying, that we can just replace this value with a quoted 10 string. Well, we know that, but we needed to demonstrate what is going on here.

You can cast a variable to the many data types of an integer, boolean, float, string, array, object, or you can cast it to NULL with the unset keyword.

Screen Shot 2022-02-24 at 6.03.10 PM.png

Note also from this screenshot that there are shortcuts for integer and boolean, as int and bool, respectively. It’s actually more common than not to see these shorter abbreviations when referencing data types.

<?php
$title = (int) 'My Blog';
$numPosts = (string) 10;
?>
<h1><?= $title ?></h1>
<p><?= gettype($title) ?></p>
<h2><?= $numPosts ?></h2>
<p><?= gettype($numPosts) ?></p>

Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock