$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
Related
I'm trying to find a simpler way to create new arrays from existing arrays and values. There are two routines I'd like to optimize that are similar in construction. The form of the first one is:
$i = 0;
$new_array = array();
foreach ($my_array as $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$i++;
}
The form of the second one has not one but two different values per constant; notice that $value comes before $key in the indexing:
$i = 0;
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$i][0] = $constant; // defined previously and unchanging
$new_array[$i][1] = $value; // different for each index of $my_array
$new_array[$i][2] = $key; // different for each index of $my_array
$i++;
}
Is there a way to optimize these procedures with shorter and more efficient routines using the array operators of PHP? (There are many, of course, and I can't find one that seems to fit the bill.)
I believe a combination of Wouter Thielen's suggestions regarding the other solutions actually holds the best answer for me.
For the first case I provided:
$new_array = array();
// $my_array is numeric, so $key will be index count:
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value);
};
For the second case I provided:
// $my_array is associative, so $key will initially be a text index (or similar):
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key] = array($constant, $value, $key);
};
// This converts the indexes to consecutive integers starting with 0:
$new_array = array_values($new_array);
it is shorter, when you use the array-key instead of the $i-counter
$new_array = array();
foreach ($my_array as $key => $value) {
$new_array[$key][0] = $constant; // defined previously and unchanging
$new_array[$key][1] = $value; // different for each index of $my_array
}
Use array_map:
$new_array = array_map(function($v) use ($constant) {
return array($constant, $v);
}, $my_array);
If you want to use the keys too, for your second case:
$new_array = array_map(function($k, $v) use ($constant) {
return array($constant, $v, $k);
}, array_keys($my_array), $my_array);
Assuming the $constant variable is defined in the caller's scope, you'll need to use use ($constant) to pass it into the function's scope.
array_walk is similar, but modifies the array you pass to it, so if you want to update $my_array itself, use array_walk. Your second case then becomes this:
array_walk($my_array, function(&$val, $key) use($constant) {
$val = array($constant, $val, $key);
});
In both examples above for the second case, you'll end up with an associative array (i.e. with the keys still being the keys for the array). If you want to convert this into a numerically indexed array, use array_values:
$numerically_indexed = array_values($associative);
I asked a question similar to this a few days ago, check it out:
PHP - Fastest way to convert a 2d array into a 3d array that is grouped by a specific value
I think that you have an optimal way when it comes to dealing with large amount of data. For smaller amounts there is a better way as was suggested by the benchmarks in my question.
I think too that readability and understanding the code can also be an issue here and I find that things that you can understand are worth more later on than ideas that you do not really grasp as it generally takes a long time to understand them again as it can be quite confusing while debugging issues.
I would suggest, you take a look at the differences between JSON encoded arrays and serialised arrays as there can be major performance differences when working with the two. It seems that as it is now JSON encoded arrays are a more optimised format (faster) for holding and working with data however this will likely change with PHP 7. It would be useful to note that they are also more portable.
Further Reading:
Preferred method to store PHP arrays (json_encode vs serialize)
http://techblog.procurios.nl/k/n618/news/view/34972/14863/cache-a-large-array-json-serialize-or-var_export.html
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;
}
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;
}
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;
I've created this method to change every value in an array. I'm kinda new to PHP, so I think there should be a more efficient way to do this.
Here's my code:
foreach($my_array as $key => $value)
{
$my_array[$key] = htmlentities($value);
}
Is there a better way to do this?
Thank you in advance.
You'd probably be better off with array_map
$my_array = array_map( 'htmlentities' , $my_array);
You can reference the array and change it
foreach ($array as &$value) {
$value = $value * 2;
}
When you need to apply a function to the value and reassign it to the value, Galen's answer is a good solution. You could also use array_walk(), although it doesn't read as easily as a nice, simple loop.
When you only need to assign, for example, a primitive value to each element in the array, the following will work.
If your keys are numeric, you can use array_fill():
array_fill(0, sizeof($my_array), "test");
If you're using an associative array, you can probably use array_fill_keys(), with something like:
array_fill_keys(array_keys($my_array), "test");
If you mark $value as a reference (&$value) any change you make on $value will effect the corresponding element in $my_array.
foreach($my_array as $key => &$value)
{
$value = "test";
}
e.g.
$my_array = array(1,2,3,4,5,6);
foreach($my_array as &$value)
{
$value *= 5;
}
echo join($my_array, ', ');
prints
5, 10, 15, 20, 25, 30
(And there's also array_map() if you want to keep the original array.)
foreach($my_array as &$value)
{
$value = "test";
}
You could use array_fill, starting at 0 and going to length count($my_array). Not sure if it's better though.
Edit: Rob Hruska's array_fill_keys code is probably better depending on what you define as better (speed, standards, readability etc).
Edit2: Since you've now edited your question, these options are now no longer appropriate as you require the original value to be modified, not changed entirely.