How to convert a string to a number
Short answer
Put the target type in parentheses before the value:
<?php
var_dump((int) '42');
var_dump((float) '3.14');Output:
int(42)
float(3.14)Checking that a string is a number
User input is worth checking with is_numeric() before converting:
<?php
var_dump(is_numeric('42'));
var_dump(is_numeric('3.14'));
var_dump(is_numeric('42abc'));Output:
bool(true)
bool(true)
bool(false)Beware of extra characters
A cast does not report an error: it takes the digits at the start of the string and returns zero when there are none.
<?php
var_dump((int) '12abc');
var_dump((int) 'abc');Output:
int(12)
int(0)