note 126390 added to function.get-defined-vars
| From: | Qiibow at main dot php dot net | Date: | Sun, 05 Sep 2021 02:55:42 +0000 |
| Subject: | note 126390 added to function.get-defined-vars | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216866@lists.php.net to get a copy of this message | ||
get_defined_vars() is very useful for importing many values at once
into another scope (Such as User-defined functions).
Below is an example for showing some of many values and their variable-names in a table.
(useful in debugging)
You can put this user-defined function at many places in your script
to show some values (values to be changed in loops)
to check if they are what they shall be there or not.
<?php
// Set "get_defined_vars()" to 2nd argument.
function get_value_table($name_array, $gdv) {
$name_value_table = [];
foreach ($name_array as $name) :
if (!array_key_exists($name, $gdv)) :
$value = 'undefined';
elseif (is_bool($gdv[$name])) :
$value = $gdv[$name]? 'true' : 'false';
elseif (is_numeric($gdv[$name]) || is_string($gdv[$name])) :
$value = $gdv[$name];
elseif (is_array($gdv[$name])) :
$value = '<pre>'.print_r($gdv[$name],true).'</pre>';
else :
$value = (PHP_VERSION_ID >= 80000)? get_debug_type($gdv[$name]) : get_type($gdv[$name]);
endif;
$name_value_table[] = '<tr><td>$'.$name.'<td>'.$value;
endforeach;
return '<table border=1>'.implode("\n",
$name_value_table).'</table>';
} // (f) get_value_table()
$_1 = 'a';
$_2 = 'b';
$_3 = [1,2];
$_4 = false;
$_5 = null;
$name_array =
['_1','_2','_3','_4','_5','_6'];
$show_id = 1;
if ($show_id === 1) :
echo get_value_table($name_array, get_defined_vars());
endif;
/*
if $show_id === 1, only shows below.
$_1 a
$_2 b
$_3 Array
(
[0] => 1
[1] => 2
)
$_4 false
$_5 null
$_6 undefined
*/
$_2 = 'c';
if ($show_id === 2) :
echo get_value_table($name_array, get_defined_vars()); // $_2 c
endif;
# if $show_id === 2, $_2 turns "c".
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 114.172.153.198)
----
Manual Page -- https://php.net/manual/en/function.get-defined-vars.php
Edit -- https://main.php.net/note/edit/126390
Del: integrated -- https://main.php.net/note/delete/126390/integrated
Del: useless -- https://main.php.net/note/delete/126390/useless
Del: bad code -- https://main.php.net/note/delete/126390/bad+code
Del: spam -- https://main.php.net/note/delete/126390/spam
Del: non-english -- https://main.php.net/note/delete/126390/non-english
Del: in docs -- https://main.php.net/note/delete/126390/in+docs
Del: other reasons-- https://main.php.net/note/delete/126390
Reject -- https://main.php.net/note/reject/126390
Search -- https://main.php.net/manage/user-notes.php