Type Casting

Casting converts a value from one data type to another.

Syntax$number = (int) "123";

PHP will often convert types automatically, but you can force a conversion using casting. Put the target type in parentheses before the value.

  • (int) — cast to integer.
  • (float) — cast to float.
  • (string) — cast to string.
  • (bool) — cast to boolean.
  • (array) — cast to array.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Cast a query-string parameter from string to integer before using it in a database WHERE clause.
  • Convert a float price to an integer number of cents for precise monetary storage.
  • Cast a non-empty string to boolean to map a form checkbox value of '1'/'0' to true/false.

More examples

Casting GET parameters to int

Casting query-string values with (int) ensures safe, predictable numbers for SQL pagination.

Example · php
<?php
$page  = (int) ($_GET['page'] ?? 1);
$limit = (int) ($_GET['limit'] ?? 20);

$offset = ($page - 1) * $limit;
echo "OFFSET $offset LIMIT $limit";

Float to int truncation

(int) always truncates toward zero, so multiply before casting for correct cent conversion.

Example · php
<?php
$price  = 9.99;
$cents  = (int) ($price * 100); // 999
$approx = (int) $price;          // 9 - truncates, not rounds

echo $cents;   // 999
echo $approx;  // 9

Casting arrays and objects

(object) and (array) casts convert between arrays and stdClass objects for API compatibility.

Example · php
<?php
$arr = ['name' => 'Bob', 'age' => 25];
$obj = (object) $arr;

echo $obj->name; // Bob

$back = (array) $obj;
echo $back['age']; // 25

Discussion

  • Be the first to comment on this lesson.