Variable Handling

PHP Variable Handling Function

empty()

empty(mixed $var): bool

Determine whether a variable is empty

The empty function equivalent to !isset($var) || $var == false.. So if the variable is isset but with a false value, it still means empty

$testCase = array(
    1 => '',
    2 => "",
    3 => null,
    4 => array(),
    5 => FALSE,
    6 => NULL,
    7=>'0',
    8=>0,
   
);

foreach ($testCase as $k => $v) {
    if (empty($v)) {
        echo "<br> $k=>$v is empty";
    }
}

// Output
// 1=> is empty
// 2=> is empty
// 3=> is empty
// 4=>Array is empty
// 5=> is empty
// 6=> is empty
// 7=>0 is empty
// 8=>0 is empty

?>

is_bool()

is_bool(mixed $value): bool

Finds out whether a variable is a boolean

$test_data = [
    'array' 	=> ['this', 'is', 'an array'],
    'is_string' => 'is string',
    'is_int'	=> 1,
    'is_bool'	=> true,
];

foreach($test_data as $key => $value) {
	$result = 'not boolean';
    if (is_bool($value)) {
    	$result = 'is boolean';
    }
    echo sprintf("%s => %s\n", $key, $result);
}

// array => not boolean
// is_string => not boolean
// is_int => not boolean
// is_bool => is boolean

is_array()

is_array(mixed $value): bool

Finds whether a variable is an array

$test_data = [
    'array' 	=> ['this', 'is', 'an array'],
    'is_string' => 'is string',
    'is_int'	=> 1,
    'is_bool'	=> true,
];

foreach($test_data as $key => $value) {
	$result = 'not array';
    if (is_array($value)) {
    	$result = 'is array';
    }
    echo sprintf("%s => %s\n", $key, $result);
}

// array => is array
// is_string => not array
// is_int => not array
// is_bool => not array

intval()

intval(mixed $value, int $base = 10): int

Get the integer value of a variable

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
echo intval(false);                   // 0
echo intval(true);                    // 1

gettype()

gettype(mixed $value): string

Get the type of a variable

$data = [
	1, 
	1., 
	NULL, 
	new stdClass, 
	'foo'
];

foreach ($data as $value) {
    echo gettype($value), "\n\n";
}

// integer

// double

// NULL

// object

// string