//ads:
?>
PHP array stringify
PHP Snippet 1:
function data_stringify($data) {
switch (gettype($data)) {
case 'string' : return '\''.addcslashes($data, "'\\").'\'';
case 'boolean': return $data ? 'true' : 'false';
case 'NULL' : return 'null';
case 'object' :
case 'array' :
$expressions = [];
foreach ($data as $c_key => $c_value) {
$expressions[] = data_stringify($c_key).' => '.
data_stringify($c_value);
}
return gettype($data) === 'object' ?
'(object)['.implode(', ', $expressions).']' :
'['.implode(', ', $expressions).']';
default: return (string)$data;
}
}
PHP Snippet 2:
var_dump( data_stringify(-1 ) === '-1' );
var_dump( data_stringify(-1.1 ) === '-1.1' );
var_dump( data_stringify(123e1 ) === '1230' ); # exponential notation
var_dump( data_stringify(0x123 ) === '291' ); # hexadecimal notation
var_dump( data_stringify(01234 ) === '668' ); # octal notation
var_dump( data_stringify(0b101 ) === '5' ); # binary notation
var_dump( data_stringify('?123') === "'?123'" );
var_dump( data_stringify('123?') === "'123?'" );
var_dump( data_stringify(true ) === 'true' );
var_dump( data_stringify(false ) === 'false' );
var_dump( data_stringify(null ) === 'null' );
PHP Snippet 3:
var_dump(
data_stringify([
100,
'200',
'item3' => 300,
'item4' => '400',
'item5' => 'value500'
]) === "[".
"0 => 100, ".
"1 => '200', ".
"'item3' => 300, ".
"'item4' => '400', ".
"'item5' => 'value500']"
);
PHP Snippet 4:
var_dump(
data_stringify((object)[
'prop1' => 100,
'prop2' => '200',
'prop3' => 'value300'
]) === "(object)[".
"'prop1' => 100, ".
"'prop2' => '200', ".
"'prop3' => 'value300']"
);
PHP Snippet 5:
var_dump(
data_stringify([
100,
'200',
'item3' => (object)['prop1' => 1, 'prop2' => '2', 'prop3' => 'value3'],
'item4' => '400',
'item5' => 'value500'
]) === "[".
"0 => 100, ".
"1 => '200', ".
"'item3' => (object)['prop1' => 1, 'prop2' => '2', 'prop3' => 'value3'], ".
"'item4' => '400', ".
"'item5' => 'value500']"
);
PHP Snippet 6:
var_dump(
data_stringify((object)[
'prop1' => 1,
'prop2' => '2',
'prop3' => [100, '200', 'item3' => '300', 'item4' => 'value400'],
'prop4' => 'value4'
]) === "(object)[".
"'prop1' => 1, ".
"'prop2' => '2', ".
"'prop3' => [0 => 100, 1 => '200', 'item3' => '300', 'item4' => 'value400'], ".
"'prop4' => 'value4']"
);