Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Data Type Check
<?php
// data to be tested
$data = [
null,
false,
true,
0,
1,
'',
'hello',
array(),
array(1, 2, 3),
new \stdClass,
function () {
return true;
}
];
foreach ($data as $value) {
// format name for value being tested
if (is_string($value)) {
$valueName = '"' . $value . '"';
} elseif (is_bool($value)) {
$valueName = ($value) ? 'true' : 'false';
} elseif (is_null($value)) {
$valueName = 'NULL';
} elseif (is_array($value)) {
$valueName = 'Array(' . count($value) . ')';
} elseif (is_object($value)) {
if ($value instanceof \Closure) {
$valueName = 'Closure';
} else {
$valueName = 'Object';
}
} else {
$valueName = $value;
}
// run the tests
if ($value == false) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is false (loosely typed)' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not false (loosely typed)' . PHP_EOL;
}
if ($value === false) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is false (strictly typed)' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not false (strictly typed)' . PHP_EOL;
}
if ($value == true) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is true (loosely typed)' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not true (loosely typed)' . PHP_EOL;
}
if ($value === true) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is true (strictly typed)' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not true (strictly typed)' . PHP_EOL;
}
if (empty($value)) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is empty' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not empty' . PHP_EOL;
}
if ($value == null) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is null (loosely typed)' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not null (loosely typed)' . PHP_EOL;
}
if (is_null($value)) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is null (strictly typed)' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not null (strictly typed)' . PHP_EOL;
}
if (isset($value)) {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is set' . PHP_EOL;
} else {
echo $valueName . ' (typeof ' . strtolower(gettype($value)) . ') is not set' . PHP_EOL;
}
// line separation between tests
echo PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment