Cast string to integer
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
Cast string to float
$num = floatval("10.1"); // 10.1
$num = floatval('122.34343The'); // 122.34343
$num = floatval('The122.34343'); // 0
Cast integer to boolean
$val = (bool)-1; // true
$val = (bool)0; // false
$val = (bool)1; // true
$val = (boolean)0; // false, same as (bool)
Cast string to boolean
$val = (bool)""; // false
$val = (bool)"0"; // false
$val = (bool)"1"; // true
$val = (bool)"foo"; // true
$val = (bool)"false"; // true <--------------
$val = (bool)"true"; // true
$val = (boolean)"foo"; // same as (bool), true
Cast integer to float
$val = (float)10;
$val = (double)10; // Same as (float)
$val = (real)10; // Same as (float)
Cast integer to string
$val = 10 . ""; // "10"
$val = 10.""; // Error
Cast bool to int
$val = (int)true; // 1
$val = (int)false; // 0
Cast bool to string
$bool = true;
$val = ($bool) ? 'true' : 'false'; // "true"
Cast float to integer
echo intval(42.1); //42
echo intval(42.9); //42
Cast float to boolean
$val = (bool)0.0; // false, only 0.0 value is false.
$val = (boolean)0.0; // false, same as (bool)
$val = (bool)-1.0; // true, any non-zero value is true.
Cast float to string
$val = (string)10.1; // "10.1"
Check if string starts with a specified string
function startsWith( $fullString, $part ) {
return strncmp($fullString, $part, strlen($part)) === 0;
}
$val = startsWith( "abcdef", "ab" ); // true
$val = startsWith( "abcdef", "cd" ); // false
Finds whether a variable is an array
$arr = array('this', 'is', 'an array');
$val = is_array( $arr ); // true
Check if variable is Not a Number
$number = is_numeric(123); //true
$number = is_numeric("123"); //true
$number = is_numeric("hello") //false
$not_a_number = !is_numeric(123); //false
$not_a_number = !is_numeric("hello") //true
Check if strings ends with a specified string
function endsWith( $haystack, $needle ) {
return $needle === "" || (substr($haystack, -strlen($needle)) === $needle);
}
Get actual url
$url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
Parse JSON string
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
json_decode( $json );
// Result:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Ternary if
$var = 5;
$greater_than_two = ($var > 2 ? true : false); //true
Cast array to object
$object = (object)$array;
Delay action some time
$seconds = 5;
sleep( $seconds )