changing a php variable name throughout for loop - php

I have an array that I want to rename so that the values are stored depending on what number the for loop is on. I tried something like this but its giving me an error.
for ($i =0;$i<4;$i++){
$array.$i = array();
push stuff into array;
}
So at the next iteration the array is called array1, then array2 and so forth. What is the best way to do this.

To literally answer your question:
$arrayName = 'array' . $i;
$$arrayName = array();
$$arrayName[] = ...
What you really want is a multidimensional array though:
$array[$i] = array();
$array[$i][] = ...;

You want to use variable variables, in which the double dollar sign indicates that the name of the variable is taken from a variable.
$varname = "array";
for ($i =0;$i<4;$i++){
$newvarname = $varname . $i
$$newvarname = new array()
push stuff into array;
}
I would add that in these cases, a simpler solution is often to use an array in which the desired variable names are indices. So instead of creating $array1, $array2, and so forth, you'd have:
$arrays = array (
'array1' => array(stuff),
'array2' => array(stuff),
'array3' => array(stuff),
'array4' => array(stuff)
}
At least, I find it easier to keep track of.

You should be able to reference the array using the $$ notation for variable variables (see: http://www.php.net/manual/en/language.variables.variable.php).
So, something like this should work (untested):
for ($i =0;$i<4;$i++){
$thisArrayName = 'array'.$i;
$$thisArrayName = array();
push stuff into array;
}

You need array of array
for ($i =0;$i<4;$i++){
$array[$i] = array();
push stuff into array;
}

Related

How to count and output variables named in a specific numeric pattern

I have created few different strings with similar names, and I would like to display them all.
However, I will need to do this dynamically, because I will adding more of them, later on.
These strings are called:
$group1
$group2
$group3
$group4
My idea is to somehow count them all, and then display them with for loop. I just need help with counting part.
Though arrays are definitely the superior and appropriate solution in this case, since you insist in the comments that separate variables are required, you can solve this using a while loop to check for the existence of such consecutively named variables, creating the variable names dynamically with {}.
For example:
$group1 = '123';
$group2 = '456';
$group3 = '789';
$i=1;
while ($string = ${'group'.$i}) {
echo $string;
$i++;
}
Note how ${'group'.$i} dynamically creates each variable name. Also, naturally this approach would fail if the variables are not named consecutively (e.g. if you have $group1 followed by $group3). As said, you should definitely use an array for this.
See a live demo
Associative arrays are designed exactly for this:
$arr = array(
"group1" => "string1",
"group2" => "string2",
"group3" => "string3",
"group4" => "string4",
);
Now to get the length of your array:
$num = count($arr);
To access the first element
$firstElement = $arr["group1"];
Alternatively you can use an indexed array (access elements by their position):
$arr = array("string1", "string2", "string3", "string4");
$firstElement = $arr[0];
$num = count($arr);
you can use this to count+loop
$arr=array();
$add_to=array_push($arr,$group1);
$add_to=array_push($arr,$group2);
$add_to=array_push($arr,$group3);
$add_to=array_push($arr,$group4);
//count
echo count($arr);
//loop
foreach($arr as $key=>$value){
echo $value;
}

How to use string values from one array as indexes for another array in PHP

I've splitted a string into array, giving a delimitator. So, this new array created, will contain values that I would want to use as indexes for another given array.
Having a situation like this:
// my given array
$array['key1']['key2']['a_given_key']['some_other_given_key'] = 'blablabl';
// the value of my given array
$value = $array['key1']['key2']['a_given_key']['some_other_given_key'];
$string = "key1;key2";
$keys = explode(";", $string);
I want to call dinamically (during the execution of my PHP script) the value of the given array, but, using as indexes all the values of the array $keys, and in addition appending the indexes ['a_given_key']['some_other_given_key'] of my given array.
I hope I have been clear.
Many thanks.
To make it work you have to use references. Below code should work as you expect:
<?php
$string = "key1;key2;key3;key4";
$keys = explode(";", $string);
$array['key1']['key2']['key3']['key4']['a_given_key']['some_other_given_key'] = 'blablabl';
$ref = & $array;
for ($i=0, $c = count($keys); $i<$c ; ++$i) {
$ref = &$ref[$keys[$i]];
}
echo $ref['a_given_key']['some_other_given_key'];
$value = $ref['a_given_key']['some_other_given_key'];
echo $value;
?>
I would like to add that just after using reference you should unset it using:
unset($ref);
If you don't do this and many lines later you run for example $ref = 2; it will modify your source array so you have to remember about unsetting references just after it's no longer in use.

Declare variables on the fly using for loop

I am not sure if its a good idea, but i just thought it would be less tedious and much easier to declare variables on the fly using a for loop:
$val.$i = $row1[$i];. Now after trying this, this obviously isn't the right thing to do. Is there anyway i can improve this and not declare separate variables.
Maybe this will give a clearer picture:
for($i = 1; $i < 5; $i++) {
$val.$i = $row1[$i];
}
Now i want to achieve $val1 using $val.$i.
As others have posted, using an associative or 0-based array would be a far better implementation, but you can implement the solution just as you have requested using PHP's variable variable names:
for ($i = 1; $i <= 5; $i++)
{
${"val".$i} = "this is value " . $i;
}
echo "$val1<br />$val2<br />$val3<br />$val4<br />$val5";
Will output:
this is value 1
this is value 2
this is value 3
this is value 4
this is value 5
In PHP you can define variables by name.
Example:
$foo = 'bar';
$$foo = 'baz';
echo $bar; // echoes 'baz'
So in your case, it would look like:
$var = 'val'.$i;
$$var = $arr[$i];
Why you would do that, I have no idea.
A better system (imho) is to use list() construct:
list($val1, $val2, $val3) = $arr;
You could create an associative array and then use extract:
$arr = array();
// ...
$arr[$val.$i] = $row1[$i];
// ...
extract($arr);
Mind you, it will probably be better to use the array in the first place.
I believe you're trying to get all the data you are reading from your database into one easy to access place. All you need to do is shove each row into an array:
$allTheThings[] = $row1;
You'll end up with a two dimensional array where the first key is the row number and the second key is the column number.
I am not getting full picture of what you are trying to do, but to convert arrays into objects you would do this:
$val = (object) $row1;

call_user_func_array + array_intersect with an array of array names, possible?

Sorry for the confusing title...
I need to perform an array_intersect() against a variable number of arrays. To do this it seems I need to use the call_user_func_array() function, however, this doesn't seem to be working and gives me the error:
Warning: array_intersect() [function.array-intersect]: Argument #1 is not an array in...
But, if I "print_r" the array to make sure then I see that it is an array:
Array ( [0] => arr_0 [1] => arr_1 )
My code (trimmed to just show the broken part):
$i = 0;
$arr_results = array();
foreach($arr_words as $word) {
$arrayname = "arr_".$i;
$$arrayname = array();
while ($row = mysql_fetch_assoc($search)) {
array_push($$arrayname, $row['id']);
}
array_push($arr_results, "$arrayname");
$i++
}
$matches = call_user_func_array('array_intersect',$arr_results);
In the full code I'm populating the arrays in the foreach loop with data obtained from sql queries.
From my comments:
"$arrayname" is a string, not an array. call_user_func_array will pass each element in $arr_results as argument to array_intersect. array_intersect expects arrays as arguments, but each item in $arr_results is a string, not an array.
All you have to do is create an array of arrays instead of array names:
$arr_results = array();
foreach($arr_words as $word) {
$ids = array();
while ($row = mysql_fetch_assoc($search)) {
$ids[] = $row['id'];
}
$arr_results[] = $ids;
}
$matches = call_user_func_array('array_intersect',$arr_results);
I turn $arrayname into an array with $$arrayname = array();
Right, you create a variable, lets say arr_0 which will point to array. But there is still a difference between the variable name arr_0 and the string containing the variable name "arr_0". You create an array of strings, and that just won't work. PHP does not know that the string contains a name of a variable. For example, consider this:
$arr = "arr_0";
echo $arr[0];
Based on your logic, it should output the first element of the array, but it does not, because $arr is a string, not an array, although it contains the name of a variable.
You'd have to use eval, but you really should not. You could also use variable variables again:
array_push($arr_results, $$arrayname);
that would work as well, but as I said, variable variables are confusing and in 99% of the cases, you are better of with an array.

Change variable name in loop

$index = 0;
foreach ($sxml->entry as $entry) {
$array + variable index number here = array('title' => $title);
$index++;
}
I'm trying to change an array name depending on my index count. Is it possible to change variable name (ie. $array1, $array2 $array3 etc.) in the loop?
Edit:
After the loop has finished, I will generate a number number (depending on the count of $index) and then use this array... probably it's a stupid way of accomplishing what Im trying to do, but I don't have a better idea.
You might want to try this instead:
$index = 0;
$arrays = array();
foreach ($sxml->entry as $entry) {
$arrays[$index] = array('title' => $title);
$index++;
}
While it is technically possible to do what you are asking, using an array of arrays will probably work better from you.
This type of indexing is exactly what arrays are designed for, you have a lot of items and want to be able to refer to them by number.
Unless you have a very specific reason to use the name of the variable to represent it's number you will probably have a much simpler time using it's index in the outer array.
Yes you can user an associate array. Generating a string dynamically based on the iteration number and using that as a key in the array.
You can use variable variables. php.net
PHP supports Variable variables:
$num = 1;
$array_name = 'array' . $num;
$$array_name = array(1,2,3);
print_r($array1);
http://php.net/manual/en/language.variables.variable.php

Categories