I know there are a lot of similar questions on here, and I think I've read them all. My problem is that I am attempting to loop through a list of arrays and grab one value from each. The arrays have been set up by a third party, and I don't have the access to configure how I am receiving them. Here's what I have so far:
for ($i = 0; $i < $length; $i++) {
// Both of these work and return the value I need
echo $post->related_credits_0_related_show[0];
echo "{$post->related_credits_0_related_show[0]}"
// But none of these do, and I need to loop through a handful of arrays
echo "{$post->related_credits_{$i}_related_show[0]}";
echo "{$post->related_credits_${i}_related_show[0]}";
echo "{$post->related_credits_{${i}}_related_show[0]}";
echo "{$post->related_credits_".$i."_related_show[0]}";
}
I've tried many (many!) more combinations that I won't include. I've also tried converting $i to a string. Been knocking my head against this for awhile.
Thanks ahead of time for any help.
You need to use variable variables here. The basic usage is as follows:
$var = 'Hello there!';
$foo = 'var';
echo $$foo;
^^--- note the double $-sign
This will output:
Hello there!
Instead of $$foo, you can also write the following:
echo ${"$foo"};
If the variable name is more complex, you can can also do:
echo ${"some_stuff_{$foo}_more_stuff"};
In this case, the string that denotes the variable name contains a variable, and that variable is also wrapped inside curly braces ({}). This is done in order to avoid problems with constants, array indexes etc. But if your use-case doesn't involve any of those, you don't have to worry about it.
For your specific problem, you can use the following:
for ($i=0; $i < $length; $i++) {
$post->{"related_credits_{$i}_related_show"}[0];
}
Or, if you prefer concatenation:
for ($i=0; $i < $length; $i++) {
$res = $post->{'related_credits_'.$i.'_related_show'}[0];
}
See the documentation on Variable Variables for more information.
You can use this:
$varname = "related_credits_$i_related_show";
$array = $post->$varname;
echo $array[0];
A shorter form would be:
$post->{"related_credits_{$i}_related_show"}[0];
Here you find all about so called "variable variables" : http://www.php.net/manual/en/language.variables.variable.php
Related
I'm following a tutorial and this piece of code came up:
for ($i=0; $i < $inlen ; ++$i) {
if (isset($this->morse[$in{$i}])) {
$out .= $this->morse[$in{$i}];
}
return $out;
}
$in is the key we're looking for in the morse array, but what does the $i in curly brackets represent in regards to the key=>value?
Thank you.
In this case, this is not part of a variable variable but rather String access (like getCharAt()). See the manual for more information.
$in{$i}
Becomes the character at $ith position of the string $in.
${'in'.$i}
Would be the variable variable in$i ($in0, $in1, ...)
This also makes sense as $inlen supposedly is strlen($in) and so the loop goes through each character of $in, one at a time.
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. :/
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;
im trying to create an array from a loop in PHP.
I want the array to end up something like $array(100,100,100,100), this is my code:
$x = 0;
while($x < 5){
$array[$x] = 100;
$x++;
}
echo $array[0];
It outputs 1 instead of 100.
Can someone tell me where i'm going wrong.
Even though it works perfectly for me, you should be initialising the variable beforehand.
$array = array();
For example, if $array is non-empty string, you will see the output of 1.
You can just use the predefined array_fill function for that:
$array = array_fill(0, 5, 100);
The other answers pretty much cover this. I would, however, recommend you use a for loop for this instead of a while loop if you're going to use a loop rather than a function to do it.
$array = array();
for($x=0; $x<5; $x++) {
$array[$x] = 100;
}
In fact, you could make this even shorter.
$array = array();
for($x=0; $x<5; $array[$x++]=100);
It's perfectly valid to have a for loop statement instead of a block. And blocks can go anywhere too; they don't need an if statement, for loop, while loop, or whatever, before them.
I have a loop like this below:
foreach ($header as $i) {
$i += $i;
}
I am trying to load a variable ($i) and then outside of that loop echo that variable like this below:
echo $i;
However it always returns 0;
Is it possible to get it to return the value that it created in the loop?
You can use implode() to combine all the values.
$all = implode('', $header);
http://php.net/implode
$i is re-assigned every time the loop iterates.
create a variable outside the loop, add to it during the loop, and echo again outside of it.
$outside_var = 0;
foreach ($header as $i) {
$outside_var += $i;
}
echo $outside_var;
foreach ($header as $i) {
$i += $i;
}
The above code has many problems. Other answers solve them, but with bare explanations, so you might find this helpful. For the purposes of this answer, I will assume $header contains array('a', 'b', 'c'), and that your intention was to concatenate the values.
Firstly, you're using the numeric addition operator += instead of the string concatenation operation .=. This is why $i is always 0: The values of $header are converted to integers each time you attempt to add with +=, assuming they don't start with numbers, they will always convert to the integer 0.
Secondly, if you were concatenating with .=, you'd be assigning to $i each time through the loop, so its previous value would be destroyed. On the first pass of the loop, you're effectively doing this:
$i = 'a';
$i .= $i' // aa
On the second pass, you're doing this:
$i = 'b';
$i .= $i; // bb
And so on. You need to use a different variable to store each element of the array and hold the concatenated values. Otherwise, when the loop exists, $i will always be the last value of the array, duplicated.
Finally, you should always declare your variables before attempting to read from them, which is implied by all the shorthand (+=,.=,*=,etc) operators. It's a very good idea to include E_NOTICE in error_reporting in php.ini so that you'll see the notice this raises.