Casting

13 September 2019 devTechnology
Share with:

As a not so experienced PHP dev – there are plenty of things I learn on daily basis, but one thing I should really remember using is casting.
Basically casting i changing the data type of a variable from one to another. Yes, I know – this is PHP, the language where an array can become a boolean, but still – there are people who use data types.

Generally in PHP you don’t need to define the data type – it’s automatically ‘assumed’ when it’s defined (don’t tell SJWs about it). So if you define:

$variable = 1;

it will assume it’s an integer, just as

$variable = "1";

will assume it’s a string.

Casting is a way of changing the data type:

$a = '3' //string
(int)$a //will be considered as a string

You can use it to cast boolean or null into a string


if ((int)$variable === 0) {
//will go here if the variable is '0', 0, null, false
}