I have unknown number of variables, for example:
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
I count all defined vars with $arr = get_defined_vars();
How can I count number of vars - in his case number of all arrays?
I used foreach
, but maybe I don't do this properly.
$i = 0;
foreach ($arr as $value) {
$i++;
echo '<br>';
foreach ($value as $val) {
echo $val.',';
}
}
echo $i;
I don't know why result is 8 :/
Try this:
<?php
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
$variable_s = 'adsfadfdfa';
$variable_n = 22;
$vararr = get_defined_vars();
// We want to exclude all the superglobals
$globalarrays = array(
'GLOBALS',
'_SERVER',
'_POST',
'_GET',
'_REQUEST',
'_SESSION',
'_COOKIE',
'_ENV',
'_FILES'
);
$narrays = 0;
foreach($vararr as $key => $variable) {
if ( !in_array($key, $globalarrays) && is_array($variable) ) {
echo $key . ' is an array<br />';
$narrays++;
}
}
echo '# arrays = ' . $narrays;
Notes:
Result:
number_one is an array
number_two is an array
number_three is an array
number_four is an array
# arrays = 4
The function get_defined_vars()
gets all of the variables that are defined currently in the server including environment and server variables.
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
$arr = get_defined_vars();
print_r($arr);
Try this code and see the output in your browser. I'm sure you'll get to know how many variables are actually defined(including those defined by you)
For Reference: http://php.net/manual/en/function.get-defined-vars.php
it is all because, get_defined_vars()
returns certain predefined indexes like GLOBALS
, _POST
, _GET
, _COOKIE
, _FILES
and other indexes which are user defined, here in your case, those are number_one, number_two, number_three
and number_four
for more details on get_defined_vars()
you can refer the link
As the user defined indexes, are only after predefined indexes, you can use array_slice
to slice your defined array.
$number_one = array(21,5,4,33,2,45);
$number_two = array(1,5,14,23,42,35);
$number_three = array(13,33,45,17,2,7);
$number_four = array(2,44,5,21,23,33);
$arr = get_defined_vars();
$arr = array_slice($arr, 5, count($arr));
echo count($arr);
This prints the 4.