PHP Basics
Functions in PHP
Working with Forms
Working with Files
Working with Databases
Advanced PHP Techniques

Type casting in PHP allows you to convert a variable from one data type to another. This can be particularly useful when you need to ensure that a variable is of a specific type for operations that require it. PHP provides several ways to perform type casting.

Basic Syntax for Type Casting

The basic syntax for type casting in PHP is to prepend the desired data type in parentheses before the variable you want to cast. Here are some examples:

				
					$variable = "10"; // String type

// Casting to integer
$integerVar = (int) $variable;

// Casting to float
$floatVar = (float) $variable;

// Casting to string
$stringVar = (string) $variable;

// Casting to boolean
$boolVar = (bool) $variable;

// Casting to array
$arrayVar = (array) $variable;

// Casting to object
$objectVar = (object) $variable;

				
			

Common Type Casts in PHP

1. Integer:

				
					$var = "123";
$intVar = (int) $var;

				
			

This converts the string ‘"123"‘ to the integer ‘123‘.

2. Float/Double:

				
					$var = "123.45";
$floatVar = (float) $var;

				
			

This converts the string ‘"123.45"‘ to the float ‘123.45‘.

3. String:

				
					$var = 123;
$stringVar = (string) $var;

				
			

This converts the integer ‘123‘ to the string ‘"123"‘.

4. Boolean:

				
					$var = 1;
$boolVar = (bool) $var;

				
			

This converts the integer ‘1‘ to the boolean ‘true‘.

5. Array:

				
					$var = "hello";
$arrayVar = (array) $var;

				
			

This converts the string ‘"hello"‘ to an array with one element.

6. Object:

				
					$var = array("key" => "value");
$objectVar = (object) $var;

				
			

This converts the array to an object.

Type Juggling

PHP is a loosely typed language, which means it automatically converts types based on the context (type juggling). For example, if you add a string and an integer, PHP will attempt to convert the string to an integer:

				
					$var1 = "5";
$var2 = 10;
$result = $var1 + $var2; // $result will be 15

				
			

Checking Data Types

You can check the type of a variable using functions like ‘gettype()‘ or ‘var_dump()‘:

				
					$var = 123;
echo gettype($var); // Outputs: integer

$var = "Hello";
var_dump($var); // Outputs: string(5) "Hello"

				
			

Example of Type Casting

Here is a full example illustrating type casting in PHP:

				
					<?php
// Original variables
$var1 = "123";
$var2 = "45.67";
$var3 = 1;

// Type casting
$intVar = (int) $var1;
$floatVar = (float) $var2;
$boolVar = (bool) $var3;

// Output the results
echo "Integer: $intVar\n";   // Outputs: Integer: 123
echo "Float: $floatVar\n";   // Outputs: Float: 45.67
echo "Boolean: $boolVar\n";  // Outputs: Boolean: 1
?>

				
			

By understanding and using type casting effectively, you can write more robust and predictable PHP code.

Scroll to Top