PHP Casting

PHP supports several types of casting, including:

  • Integers: Casting to integers using (int) or (integer).
  • Floats: Casting to floats using (float) or (double).
  • Strings: Casting to strings using (string).
  • Booleans: Casting to booleans using (bool) or (boolean).
  • Arrays: Casting to arrays using (array).
  • Objects: Casting to objects using (object).

Example of PHP Casting

<?php
$string = '10';

echo (int)$string . "\n";
// Outputs: 10
echo (float)$string . "\n";
// Outputs: 10
$string = 'Hello, World!';

echo (int)$string . "\n";
// Outputs: 0
echo (float)$string . "\n";
// Outputs: 0

$bool = true;

echo (int)$bool . "\n";
// Outputs: 1
echo (float)$bool . "\n";
// Outputs: 1.0
echo (string)$bool . "\n";
// Outputs: '1'

$array = array(1, 2, 3);

echo (string)$array . "\n";
// Outputs: 'Array'

$object = new stdClass();
$object->name = 'John';
$object->age = 30;

echo (string)$object . "\n";
// Outputs: 'Object of class stdClass could not be converted to string'

$null = NULL;

echo (int)$null . "\n";
// Outputs: 0
echo (float)$null . "\n";
// Outputs: 0.0
echo (string)$null . "\n";
// Outputs: ''

$undefined;

echo (int)$undefined . "\n";
// Outputs: 0
echo (float)$undefined . "\n";
// Outputs: 0.0
echo (string)$undefined . "\n";
// Outputs: ''
?>

Output:

10
10
0
0
1
1.0
'1'
'Array'
'Object of class stdClass could not be converted to string'
0
0.0
''
0
0.0
''

Explanation: This example demonstrates the use of casting in PHP, including casting to integers, floats, strings, booleans, arrays, and objects.