Conversion casts turn text into numbers or values back into text.

integer cast `(int)` converts numeric text into an integer that arithmetic can use.

Type Conversion

raw
type_conversion.php
Replay: real traced execution (multi-file project)
<?php
$raw = "12";
$value = (int) $raw;
$doubled = $value * 2;
$label = (string) $doubled . " points";

echo "raw=" . $raw . "\n";
echo "doubled=" . $doubled . "\n";
echo $label . "\n";
<?php
$raw = "7";
$value = (int) $raw;
$doubled = $value * 2;
$label = (string) $doubled . " points";

echo "raw=" . $raw . "\n";
echo "doubled=" . $doubled . "\n";
echo $label . "\n";
<?php
$raw = "20";
$value = (int) $raw;
$doubled = $value * 2;
$label = (string) $doubled . " points";

echo "raw=" . $raw . "\n";
echo "doubled=" . $doubled . "\n";
echo $label . "\n";
  1. $raw ← 12, $value ← 12, $doubled ← 24, $label ← 24 points

    1<?php2$raw→ 12 = "12"; //@raw="7", "20"3$value→ 12 = (int) $raw12;4$doubled→ 24 = $value12 * 2;5$label→ 24 points = (string) $doubled24 . " points";67echo "raw=" . $raw12 . "\n";8echo "doubled=" . $doubled24 . "\n";9echo $label24 points . "\n";
    outputraw=12
    doubled=24
    24 points
  1. $raw ← 7, $value ← 7, $doubled ← 14, $label ← 14 points

    1<?php2$raw→ 7 = "7";3$value→ 7 = (int) $raw7;4$doubled→ 14 = $value7 * 2;5$label→ 14 points = (string) $doubled14 . " points";67echo "raw=" . $raw7 . "\n";8echo "doubled=" . $doubled14 . "\n";9echo $label14 points . "\n";
    outputraw=7
    doubled=14
    14 points
  1. $raw ← 20, $value ← 20, $doubled ← 40, $label ← 40 points

    1<?php2$raw→ 20 = "20";3$value→ 20 = (int) $raw20;4$doubled→ 40 = $value20 * 2;5$label→ 40 points = (string) $doubled40 . " points";67echo "raw=" . $raw20 . "\n";8echo "doubled=" . $doubled40 . "\n";9echo $label40 points . "\n";
    outputraw=20
    doubled=40
    40 points

Follow the Conversion

  1. $raw starts as "12".
  2. (int) $raw gives the number 12.
  3. $doubled = $value * 2 becomes 24.
  4. $label becomes 24 points.
  5. The program prints raw=12, doubled=24, and 24 points. | raw | doubled | final line | | --- | --- | --- | | 7 | 14 | 14 points | | 12 | 24 | 24 points | | 20 | 40 | 40 points |

Exercise: type_conversion.php

Reproduce 24 points, then use the pinned raw values 7 and 20 to predict each doubled value and final line.