Skip to content

Instantly share code, notes, and snippets.

@NewEXE
Last active August 18, 2021 23:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NewEXE/7d3b89c49f059fd339dcb8177e204612 to your computer and use it in GitHub Desktop.
Save NewEXE/7d3b89c49f059fd339dcb8177e204612 to your computer and use it in GitHub Desktop.
Convert anything to string (PHP)
<?php
/**
* @param mixed $value Value of any PHP type.
* @return string Value as readable string.
*/
function toString($value, $compactArray = true): string
{
$data_type = '';
if (is_array($value)) {
if ($compactArray) {
$value = json_encode($value);
} else {
$value = print_r($value, true);
}
} elseif (is_object($value)) {
$data_type .= get_class($value);
if ($value instanceof \Exception) {
$data_type .= ': Exception';
$value = print_r([
'message' => $value->getMessage(),
'code' => $value->getCode(),
'file' => $value->getFile(),
'line' => $value->getLine(),
'trace' => $value->getTraceAsString()
], true);
} else {
$value = print_r($value, true);
}
} elseif (is_resource($value)) {
$data_type .= get_resource_type($value);
$value = (string) $value;
} elseif (is_bool($value)) {
$value = $value ? 'true' : 'false';
} elseif ($value === null) {
$value = 'NULL';
} elseif (!settype($value, 'string')) {
$value = 'Error: can\'t convert input data to string';
}
if (!empty($data_type)) {
$value = '[' . $data_type . '] ' . $value;
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment