Casting (spells)
In PHP, casting is just a fancy word for changing a variable’s data type. You might want to do this when you’re working with mixed data — like values coming from forms or APIs — and need to make sure everything is the right type before you manipulate it.
You can cast using these simple statements:
(string)→ turns something into text(int)→ converts to integer(float)→ converts to a floating-point number(bool)→ converts to true/false(array)→ turns the value into an array(object)→ turns it into an object(unset)→ basically wipes it out (NULL)
Let’s go through what actually happens behind the scenes.
Say you have a few variables of different types:
$a = 5; // int
$b = 5.34; // float
$c = "hello"; // string
$d = true; // bool
$e = NULL; // null
Casting them all to strings looks like this:
$a = (string) $a;
$b = (string) $b;
$c = (string) $c;
$d = (string) $d;
$e = (string) $e;
Then var_dump() would confirm that everything’s now text.
If you cast to integers:
$c = (int) "25 plugins"; // becomes 25
$d = (int) "plugins 25"; // becomes 0 (since it starts with text)
$f = (int) true; // 1
$g = (int) NULL; // 0
So PHP tries to make sense of it — numbers at the start of a string survive, but random text doesn’t.
Casting to float works the same way, just keeping the decimal part:
$x = (float) "25.9 hours"; // 25.9
Booleans have their own logic:
0,"",false, orNULL→ becomefalse- Everything else → becomes
true
Even-1counts astruein PHP.
Arrays are interesting — most values just become arrays with one item:
$x = (array) 42;
// [0 => 42]
But if you cast an object to an array, you’ll get an associative array with the object’s property names as keys:
class Plugin {
public $name;
public $active;
public function __construct($name, $active) {
$this->name = $name;
$this->active = $active;
}
}
$plugin = new Plugin("Pretty Links", true);
var_dump((array) $plugin);
That will show something like ["name" => "Pretty Links", "active" => true].
If you go the other way and cast arrays into objects:
$tools = ["MemberPress", "Pretty Links", "ThirstyAffiliates"];
$obj = (object) $tools;
Now $obj has properties like $obj->{0} and $obj->{1} — not super readable, but it’s there. Associative arrays, on the other hand, become proper objects with named properties.
Finally, casting to (unset) is how you wipe something completely. The variable becomes NULL:
$x = "Hello";
$x = (unset) $x;
var_dump($x); // NULL