Skip to content

Commit 34c58a4

Browse files
feat: type casting
1 parent f542ee3 commit 34c58a4

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

08_type_casting.php

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
<?php
2+
3+
/*
4+
* Casting in PHP is done with these statements:
5+
* (string) - Converts to data type String
6+
* (int) - Converts to data type Integer
7+
* (float) - Converts to data type Float
8+
* (bool) - Converts to data type Boolean
9+
* (array) - Converts to data type Array
10+
* (object) - Converts to data type Object
11+
* (unset) - Converts to data type NULL
12+
* */
13+
14+
// Cast to Integer
15+
$a = 5.90;
16+
$b = "kilometers 25";
17+
$c = true;
18+
$d = NULL;
19+
20+
$a = (int)$a;
21+
$b = (int)$b;
22+
$c = (int)$c;
23+
$d = (int)$d;
24+
25+
echo "<pre/>======== Cast to Integer ======== <pre/>";
26+
var_dump($a, $b, $c, $d);
27+
28+
// Cast to Float
29+
$a = 5;
30+
$b = "kilometers 25";
31+
$c = true;
32+
$d = NULL;
33+
34+
$a = (float)$a;
35+
$b = (float)$b;
36+
$c = (float)$c;
37+
$d = (float)$d;
38+
39+
echo "<pre/>======== Cast to Float ======== <pre/>";
40+
var_dump($a, $b, $c, $d);
41+
42+
// Cast to Boolean
43+
$a = 5;
44+
$b = "kilometers 25";
45+
$c = 5.90;
46+
$d = NULL;
47+
48+
$a = (bool)$a;
49+
$b = (bool)$b;
50+
$c = (bool)$c;
51+
$d = (bool)$d;
52+
53+
echo "<pre/>======== Cast to Boolean ======== <pre/>";
54+
var_dump($a, $b, $c, $d);
55+
56+
57+
// Cast to Array
58+
$a = 5;
59+
$b = "kilometers 25";
60+
$c = 5.90;
61+
$d = NULL;
62+
63+
$a = (array)$a;
64+
$b = (array)$b;
65+
$c = (array)$c;
66+
$d = (array)$d;
67+
68+
echo "<pre/>======== Cast to Array ======== <pre/>";
69+
var_dump($a, $b, $c, $d);
70+
71+
// Cast to Object
72+
$a = 5;
73+
$b = "kilometers 25";
74+
$c = 5.90;
75+
$d = NULL;
76+
77+
$a = (object)$a;
78+
$b = (object)$b;
79+
$c = (object)$c;
80+
$d = (object)$d;
81+
82+
echo "<pre/>======== Cast to Object ======== <pre/>";
83+
var_dump($a, $b, $c, $d);
84+
85+
// Cast to NULL
86+
$a = 5;
87+
$b = "kilometers 25";
88+
$c = 5.90;
89+
$d = NULL;
90+
91+
// $a = (unset)$a; // (Deprecated since version 7.2)
92+
$a = NULL;
93+
$b = null;
94+
$c = null;
95+
$d = null;
96+
97+
echo "<pre/>======== Cast to NULL ======== <pre/>";
98+
var_dump($a, $b, $c, $d);
99+
100+
// Converting Arrays into Objects:
101+
$a = array("Volvo", "BMW", "Toyota"); // indexed array
102+
$b = array("Peter" => "35", "Ben" => "37", "Joe" => "43"); // associative array
103+
104+
$a = (object)$a;
105+
$b = (object)$b;
106+
echo "<pre/>======== Converting Arrays into Objects ======== <pre/>";
107+
var_dump($a, $b);

0 commit comments

Comments
 (0)