PHP: Type conversion

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Type conversion

Aims:

Explicit type conversion

Implicit type conversion

Implicit type conversion

Converting numeric data to strings

Example with concatenation

$num_of_students = (int) $_GET['num_of_students'];
$num_of_staff = (int) $_GET['num_of_staff'];

$num_of_students_per_staff = $num_of_students / $num_of_staff;
   
echo '<p>The staff-student ratio in your college is: ' . $num_of_students_per_staff . '</p>';

Example with interpolation

$num_of_students = (int) $_GET['num_of_students'];
$num_of_staff = (int) $_GET['num_of_staff'];

$num_of_students_per_staff = $num_of_students / $num_of_staff;
   
echo "<p>The staff-student ratio in your college is: {$num_of_students_per_staff}</p>";

Class exercise

PHP's type conversions: summary

fromto
floatint truncate the decimal places
e.g. 7.6 becomes 7
intfloat nothing much to be done
e.g. 12 becomes 12.0
int/floatstring nothing much to be done
e.g. 12 becomes '12'; 7.6 becomes '7.6'
stringint/float the start of the string is interpreted as a number, if it can be
otherwise, the string is converted to 0
e.g. '7' becomes 7; '12.2blah' becomes 12.2;
'0.5E2 ' becomes 0.5E2 (i.e. 50.0);
'Hello' becomes 0; ' 7' becomes 7

(Lots of little details suppressed here, e.g. what if you try to convert something that's too big)

Class exercise