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:
The code counts only arrays, no scalars (is_array()).
It excludes the super global arrays like GLOBALS, _POST, etc.
Result:
number_one is an array
number_two is an array
number_three is an array
number_four is an array
# arrays = 4
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.
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
Related
Consider this code:
$var = 'test';
$_POST[$test]; // equals $_POST['test']
How can I access with the same method this variable:
$_POST['test'][0];
$var = 'test[0]'; clearly doesn't work.
EDIT
Let me give a bit more information. I've got a class that builds a form.
An element is added like this:
//$form->set_element(type, name, defaultValue);
$form->set_element('text', 'tools', 'defaultValue');
This results into :
<input type="text" name="tools" value="defaultValue" />
In my class I set the value: if the form is posted, use that value, if not, use the default:
private function set_value( $name, $value='' ) {
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
return $_POST[$name];
else
return $value;
}
When I want to add multiple "tools", I would like to use:
$form->set_element('text', 'tools[0]', 'defaultValue');
$form->set_element('text', 'tools[1]', 'defaultValue');
$form->set_element('text', 'tools[2]', 'defaultValue');
But in the set_value function
that gives $_POST['tools[0]'] instead of $_POST['tools'][0]
Use any number of variables in [] to access what you need:
$test = 'test';
$index = 0;
var_dump($_POST[$test][$index]);
$test = 'test';
$index = 0;
$subkey = 'key'
var_dump($_POST[$test][$index][$subkey]);
And so on.
There's no special function to achieve what you want, so you should write something, for example:
$key = 'test[0]';
$base = strstr($key, '[', true); // returns `test`
$ob_pos = strpos($key, '[');
$cb_pos = strpos($key, ']');
$index = substr($key, $ob_pos + 1, $cb_pos - $ob_pos - 1);
var_dump($arr[$base][$index]);
Edit by LinkinTED
$key = 'test[0]';
$base = $n = substr($name, 0, strpos($key, '[') );
preg_match_all('/\[([^\]]*)\]/', $key, $parts);
var_dump($arr[$base][$parts[1][0]]);
See how when you did $_POST['test'][0]; you just added [0] to the end? As a separate reference.
You have to do that.
$_POST[$test][0];
If you need both parts in variables then you need to use multiple variables, or an array.
$var = Array( "test", "0" );
$_POST[$test[0]][$test[1]];
Each dimension of an array is called by specifying the key or index together with the array variable.
You can reference a 3 dimensional array's element by mentioning the 3 indexes of the array.
$value = $array['index']['index']['index'];
Like,
$billno = $array['customers']['history']['billno'];
You can also use variables which has the index values that can be used while specifying the array index.
$var1 = 'customers';
$var2 = 'history';
$var3 = 'billno';
$billno = $array[$var1][$var2][$var3];
I'm trying to figure out how I can use the values an indexed array as path for another array. I'm exploding a string to an array, and based on all values in that array I'm looking for a value in another array.
Example:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
// .. echo $haystack[... items..?]
The number of values may differ, so it's not an option to do just $haystack[$items[0][$items[1][$items[2][$items[3]].
Any suggestions?
You can use a loop -
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$temp = $haystack;
foreach($items as $v) {
$temp = $temp[$v]; // Store the current array value
}
echo $temp;
DEMO
You can use a loop to grab each subsequent nested array. I.e:
$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my#string#is#nested';
$items = explode('#', $var);
$val = $haystack;
foreach($items as $key){
$val = $val[$key];
}
echo $val;
Note that this does no checking, you likely want to check that $val[$key] exists.
Example here: http://codepad.org/5ei9xS91
Or you can use a recursive function:
function extractValue($array, $keys)
{
return empty($keys) ? $array : extractValue($array[array_shift($keys)], $keys) ;
}
$haystack = array('my' => array('string' => array('is' => array('nested' => 'hello'))));
echo extractValue($haystack, explode('#', 'my#string#is#nested'));
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c;$i++){
$v = '$var'.$i;
$splited = list($v) = $my_array;
}
?>
input:
$my_array
But expected output:
if I echo $var0, $var1, $var2;
hello, world, howareu
How to create dynamic PHP variables based upon the array count and then convert them into a list as a string?
You do not need list for that. $$ will suit you perfectly.
$my_array = array("hello", "world", "howareu");
foreach ($my_array as $key => $val)
{
$a = 'var'.$key;
$$a = $val;
}
echo $var0,", ", $var1,", " $var2;
Take a look here - Variable variables
Added:
or if you need count and for
for ($i = 0; $i < count($my_array); $i++)
{
$a = 'var'.$i;
$$a = $my_array[$i];
}
echo $var0,", ", $var1,", " $var2;
Of course, this line echo $var0,", ", $var1,", " $var2; sucks and looks like crap :) But in order to receive EXACTLY what you want, you need to modify variables, output like I've wrote, or use some function like implode with grue ', '.
Updated:
But if you need just that output, why not to use simple implode(', ', $my_array) :)
it's a matter of the data you need to process...if it's pretty static, you don't need the second foreach() for example, since you compare the keys anyways...
foreach($datavalueas $resultdatakey=>$resultdatavalue){
if($resultdatakey== 'A'){
//stuff for a
}
if($resultdatakey== 'B'){
//stuff for b
}
}
would become
if(isset($datavalueas['A'])){
//stuff for a
}
if(isset($datavalueas['B'])){
//stuff for b
}
since the foreach uses copies of the array, which are pretty bad for the performance...
Assuming i got your question right, you could use something like:
$array = array( 'x', 'y', 'z' );
foreach ($array as $name )
$$name = rand(1,100);
var_dump($x);
the $$ is key here, the first $ implies the variable as the second $ is used as the identifier for the variable. In this case the value being iterated over in the array. Giving us 3 variables: $x, $y, $z.
-- edit:
the correct code, besides using extract():
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i < $c;$i++){
$v = 'var'.$i;
$$v = $my_array[$i];
}
echo "$var0, $var1, $var2";
?>
You can create dynamic variables via variables variable as Mr.kovpack have stated here. In below code you can access the variables from 0 to $c-1(count of array) as per your comment to Mr.kovpack.
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
${'var'.$i} = $my_array[$i]; //Dynamic variable creation
// $splited = list($v) = $my_array;
}
echo $var0.$var1.$var2;
or you could use like below:
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
$a='var'.$i;
$$a = $my_array[$i];
}
echo $var0."-".$var1."-".$var2;
You can read more on it here
I need to convert all items in array to variables like:
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
And I want to convert it to this:
$apple = 5;
$banana = 7;
$orange = 8;
Like normal variables. Is it possible?
Seems like a silly thing to do, why not convert it into an associative array? But if you must:
foreach($item as $x) {
list($name, $val) = explode('=', $x, 2);
$$name = $val;
}
You can try to join the array and parse the string into variables
parse_str(implode('&',$item));
You can do it like this
$item[0] = "apple=5";
$item[1] = "banana=7";
$item[2] = "orange=8";
foreach($item as $row)
{
$new = explode('=',$row);
$array[$new[0]] = $new[1];
}
extract($array);
echo $apple;
echo $banana;
echo $orange;
Your array looks like someone exploded an ini file on its newlines.
Implode with newlines, then parse, then call extract() to generate the variables. (Demo)
extract(
parse_ini_string(
implode(PHP_EOL, $item)
)
);
echo "$apple $banana $orange";
Using explode() or parse_ini_string() or preg_ functions (etc.) will render the numeric values as string-type.
If you'd like the numeric values to be integer-typed, then using %d in the "format" parameter of sscanf() will be most direct. (Demo1)
foreach ($item as $string) {
[$key, $$key] = sscanf($string, '%[^=]=%d');
}
Generally speaking, I do not advise the generation of individual variable (I more strenuously advise against variable variables). Perhaps an associative array would be suitable. (Demo)
$result = [];
foreach ($item as $string) {
[$key, $result[$key]] = sscanf($string, '%[^=]=%d');
}
var_dump($result);
Is this possible?
Like make an array with all the variables that have a certain prefix?
I don't need the keys just the values, but I guess I could use array_values on the array.
If you need to do this, it's probably not written very well to begin with, but, here's how to do it :)
$foobar = 'test';
$anothervar = 'anothertest';
$foooverflow = 'fo';
$barfoo = 'foobar';
$prefix = 'foo';
$output = array();
$vars = get_defined_vars();
foreach ($vars as $key => $value) {
if (strpos($key, $prefix) === 0) $output[] = $value;
}
/*
$output = array(
'test', // from $foobar
'fo', // from $foooverflow
);
*/
http://php.net/manual/en/function.get-defined-vars.php
my eyes are bleeding a little, but I couldn't resist a one liner.
print_r(iterator_to_array(new RegexIterator(new ArrayIterator(get_defined_vars()), '/^' . preg_quote($prefix) . '/', RegexIterator::GET_MATCH, RegexIterator::USE_KEY)));
If you're talking about variables in the global scope, you could do this with $GLOBALS[]:
$newarray = array();
// Iterate over all current global vars
foreach ($GLOBALS as $key => $value) {
// And add those with keys matching prefix_ to a new array
if (strpos($key, 'prefix_' === 0) {
$newarray[$key] = $value;
}
}
If you have lots and lots of variables in global scope, this is going to be slower in execution than manually adding them all to compact(), but faster to type out.
Addendum
I would just add (though I suspect you already know) that if you have the ability to refactor this code, you are better off to group the related variables together into an array in the first place.
This, my second answer, shows how to do this without making a mess of the global scope by using a simple PHP object:
$v = new stdClass();
$v->foo = "bar";
$v->scope = "your friend";
$v->using_classes = "a good idea";
$v->foo_overflow = "a bad day";
echo "Man, this is $v->using_classes!\n";
$prefix = "foo";
$output = array();
$refl = new ReflectionObject($v);
foreach ($refl->getProperties() as $prop) {
if (strpos($prop->getName(), $prefix) === 0) $output[] = $prop->getValue($v);
}
var_export($output);
Here's the output:
Man, this is a good idea!
array (
0 => 'bar',
1 => 'a bad day',
)