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;
Related
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;
}
Why does this not work?
$w = '"one","two"';
$a = array($w);
for($i = 0; $i < count($a); $i++) {
echo $a[$i].'<br />';
}
The one above outputes: "one","two"
But This does?
$a = array("one","two");
for($i = 0; $i < count($a); $i++) {
echo $a[$i].'<br />';
}
The one above outputs:
one
two
This has to be dynamically pulled from a database. I'm storing the info as an array with quotes around each element. So, when I want to pull the data I'm just going to throw a variable for that row in an array. But, since that isn't working how do I make it work? Thank you
$w = '"one","two"';
$a = array($w);
Creates an array with one element "one","two" (check with var_dump($a);)
$a = array("one","two");
Creates an array with two elements "one" and "two"
If the data comes from the database as a string of comma-separated items, you could split them with explode(), but it is a terrible practice - you shouldn't store multiple values in a string.
In the first example, you are building an array with a single string "one","two".
In the second example, you are building an array with two strings: "one" and "two".
If you have a string like in example 1 that you want to turn into an array, you can use the php function explode():
http://php.net/manual/en/function.explode.php
All I can say is that the first method is outputting a string literal. Perhaps php doesn't doesn't understand how many items to put in your array...
Anyhow, you might try loading the strings "One" and "Two" into the array one at a time rather than at the point of declaration. :/
$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
I have a function (for ease, I'll just use count()) that I want to apply to maybe 4-5 different variables. Right now, I am doing this:
$a = count($a);
$b = count($b);
$c = count($c);
$d = count($d);
Is there a better way? I know arrays can use the array_map function, but I want the values to remain as separate values, instead of values inside of an array.
Thanks.
I know you said you don't want the values to be in an array, but how about just creating an array specifically for looping through the values? i.e.:
$arr = Array($a, $b, $c, $d);
foreach ($arr as &$var)
{
$var = count($var);
}
I'm not sure if that really is much tidier than the original way, though.
If you have a bunch of repeating variables to collect data your code is poorly designed and should just be using an array to store the values, instead of dozens of variables. So perhaps you want something like:
$totals = array("Visa"=>0,"Mastercard"=>0,"Discover"=>0,"AmericanExpress"=>0);
then you simply add to your array element (say from a while loop from your SQL or whatever you are doing)
$totals['Visa'] += $row['total'];
But if you really want to go down this route, you could use the tools given to you, if you want to do this with a large batch then an array is a good choice. Then foreach the array and use variable variables, like so:
$variables = array('a','b','c'...);
foreach ( $variables as $var )
{
${$var} = count(${var});
}
What Ben and TravisO said, but use array_walk for a little cleaner code:
$arr = Array($a, $b, $c, $d);
array_walk($arr, count);
You can use extract to get the values back out again.
//test data
$a = range(1, rand(4,9));
$b = range(1, rand(4,9));
$c = range(1, rand(4,9));
//the code
$arr = array('a' => $a, 'b' => $b, 'c' => $c);
$arr = array_map('count', $arr);
extract($arr);
//whats the count now then?
echo "a is $a, b is $b and c is $c.\n";
How do you measure "better"? You might be able to come up with something clever and shorter, but what you have seems like it's easiest to understand, which is job 1. I'd leave it as it is, but assign to new variables (e.g. $sum_a, ...).
What's better to use in PHP for appending an array member,
$array[] = $value;
or
array_push($array, $value);
?
Though the manual says you're better off to avoid a function call, I've also read $array[] is much slower than array_push(). What are some clarifications or benchmarks?
I personally feel like $array[] is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your array.
I ran this code:
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
$array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
array_push($array, $i);
}
print microtime(true) - $t;
The first method using $array[] is almost 50% faster than the second one.
Some benchmark results:
Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]
Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]
Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]
This shouldn't be surprising, as the PHP manual notes this:
If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
The way it is phrased I wouldn't be surprised if array_push is more efficient when adding multiple values. Out of curiosity, I did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.
The main use of array_push() is that you can push multiple values onto the end of the array.
It says in the documentation:
If you use array_push() to add one
element to the array it's better to
use $array[] = because in that way
there is no overhead of calling a
function.
From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Word on the street is that [] is faster because no overhead for the function call. Plus, no one really likes PHP's array functions...
"Is it...haystack, needle....or is it needle haystack...ah, f*** it...[] = "
One difference is that you can call array_push() with more than two parameters, i.e. you can push more than one element at a time to an array.
$myArray = array();
array_push($myArray, 1,2,3,4);
echo join(',', $myArray);
prints 1,2,3,4
A simple $myarray[] declaration will be quicker as you are just pushing an item onto the stack of items due to the lack of overhead that a function would bring.
Since "array_push" is a function and it called multiple times when it is inside the loop, it will allocate memory into the stack.
But when we are using $array[] = $value then we are just assigning a value to the array.
Second one is a function call so generally it should be slower than using core array-access features. But I think even one database query within your script will outweight 1000000 calls to array_push().
See here for a quick benchmark using 1000000 inserts: https://3v4l.org/sekeV
I just wan't to add : int array_push(...) returns
the new number of elements in the array (PHP documentation). which can be useful and more compact than $myArray[] = ...; $total = count($myArray);.
Also array_push(...) is meaningful when variable is used as a stack.