I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.
<?PHP
$array=array(foo, bar, baz);
foreach ($array as $option) {
// I have if statements to determine what $option_req
// and $option_status end up being, they work correctly.
$option_req="Hello";
$option_status="World";
$rh='Req_';
$sh='Status_';
$$rh.$$option=$option_req;
$$sh.$$option=$option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
?>
When the loop is finished, should this now give me six variables?
$Req_foo
$Status_foo
$Req_bar
$Status_bar
$Req_baz
$Status_baz
I have played with this a bit, searches on Google seem fruitless today.
To access some array item, just access some array item.
No loops required.
$req = array("foo" => 1,
"bar" => 2,
"baz" => 3,
);
echo $req['foo'];
plain and simple
Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:
<?php
$array = array('foo', 'bar', 'baz');
foreach ($array as $option)
{
$option_req="Hello";
$option_status="World";
$rh = 'Req_';
$sh = 'Status_';
$r_opt = $rh.$option;
$s_opt = $sh.$option;
$$r_opt = $option_req;
$$s_opt = $option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.
You could (though you should not!) do:
${$rh.$option} = ...
Variable variables don't work that way. You need to have one variable containing the string.
$opt_r = $rh.$option;
$$opt_r = $option_req;
$opt_s = $sh.$option;
$$opt_s = $option_status;
Also, make sure to quote your strings:
$array=array('foo', 'bar', 'baz');
I don't suggest using variable variables, but if you want to, this is how to do it.
Related
I have class for take values inside loop as this :
$db_user->take_phone[1];
Inside loop I need take different values for the class
$a=array("phone","name","street");
foreach($a as $aa) {
echo $db_user->take_'$aa.'[1]
}
As you can see inside the loop I need to change the value inside take_$string, but it doesn't work. I suppose there is a syntax error but I'm not sure. How can I write this to work correctly.
I've tried different ways but haven't found a solution.
You can use a variable variable, which takes the form of $var->$property. Notice the extra $.
$a = array("phone","name","street");
foreach($a as $aa) {
$var = "take_$aa";
echo $db_user->$var[1];
}
Demo: https://3v4l.org/HolHZ
You have errors php syntax. I has explained it in my example more:
<?php
$db_user = new stdClass();
$db_user->take_phone = [
'p1','p2','p3'
];
$db_user->take_name = [
'n1','n2','n3'
];
$db_user->take_street = [
's1','s2','s3'
];
$a=array("phone","name","street");
foreach($a as $aa) {
echo $db_user->{'take_'.$aa}[1];
}
I have an assignment to do but am having trouble understanding the given psuedocode :/
<?php
$bucket = new array();
print $bucket->addrocks('Rock1')->addrocks('rock2')-
>addrocks('Rock3');
echo "<h1>My Bucket</h1>";
echo "<ul>";
foreach($bucket as $rock){
echo "<li>". $rock ."</li>";
}
echo "</ul>";
?>
Now my trouble starts with understanding how they want me to construct the array after the "print" call? i am not looking for a direct answer to this just maybe a tutorial link or a finger in the right direction
Thank you in advance
In PHP, new is only used for instantiating objects Furthermore, array is a reserved word in PHP, so name your class something else. To instantiate an array in PHP you do this:
$my_array = array();
Now to add items to the array you would do this:
$my_array[] = "Rock 1";
$my_array[] = "Rock 2";
$my_array[] = "Rock 3";
To traverse the array you can use any type of loop, but usually you would just use a foreach loop.
For example:
foreach($my_array as $key => $value) {
echo $value . "<br />";
}
The problem lies in the array construction. This is how one constructs an array in PHP:
one by one:
$bucket = array();
$bucket[] = "Rock1";
$bucket[] = "Rock2";
$bucket[] = "Rock3";
All at once:
$bucket = array("Rock1","Rock2","Rock3");
The documentation: http://php.net/manual/en/language.types.array.php
Well unlikely but may be the array is not an construct but an class in your pseudocode. My assumptions depend on the use of new keyword and the user of -> and addrocks which looks like a method.
So, create a class called array (stupid I know) and get going.
However the user of foreach($bucket) also shows that it expects $bucket to be array. So decide wisely :)
May be use a magic method called __toString() inside the class and return back the array.
I feel silly for asking this, and I am sure it is something very simple. When I try to reference the variable "test" later in a script, instead of listing all 70 items in the array it only lists one.
<?php
$exclude = '/^.*\.(lck)$/i';
$directory = 'images/slide/';
$rootpath = 'images/slide/';
$pathnames = preg_grep('/^([^.])/', scandir($rootpath));
shuffle($pathnames);
foreach ($pathnames as $pathname) {
if (preg_match($exclude, $pathname)) {
} else {
$test = '["'.$directory. $pathname.'"]';
}
}
?>
If I echo "test" right below the test variable declaration it displays everything correctly. If I echo it out later it only displays one item.
It looks like you're treating test as a string, trying adding this at the start of your code:
$test = array();
And then change:
$test = '["'.$directory. $pathname.'"]';
to:
$test[] = $directory. $pathname;
On each iteration of the loop, you're overwriting the previously assigned valued of $test;
$test = '["'.$directory. $pathname.'"]';
When you display this, no matter whether straight after assignment or after the loop, you'll get the last assigned value. If you want to accumulate the values in the variable, you need to append to it, for example,
$test .= '["'.$directory. $pathname.'"]';
Alternatively, if you want your $test to be an array and contain all files in it, then your assignment should be to an array element, not to the whole variable, e.g.
$test[] = '"'.$directory. $pathname.'"';
I have some arrays that have each 4 values in them, named:
$myarray_row0
$myarray_row1
$myarray_row2
So normally I can use this echo statement to get at the values in the first array:
echo 'My value is '.$myarray_row0[0]; // This works fine
But I want to use a FOR LOOP to iterate through them and I'm getting stuck because I want to use something like:
for ($i=0; $i<=10; $i++)
{
echo 'My value is '.$myarray_row[$i][[$i]];
echo 'My value is '.$myarray_row[$i][$i+1]];
echo 'My value is '.$myarray_row[$i][[$i+2]];
echo 'My value is '.$myarray_row[$i][[$i+3]];
}
I'm not using the correct syntax for the $i's and the brackets needed... I'm TRYING (but failing) to get the echo to spit out the arrays contents, such as:
$myarray_row0[0]
$myarray_row0[1]
$myarray_row0[2]
$myarray_row0[3]
etc
Note that it's not truly a multidimensional array, it's one dimensional, but it almost LOOKS like it is multi-dimensional since the array names have 'row0', 'row1', 'row2', etc in them.
Anyone know the syntax for getting a variable like $myarray_row0[1] to be echo'ed using the $i's that are available inside the for loop?
THANKS!
You'd need to use a variable variable name. (its been a while since ive used php so might be wrong)
for ($i=0;$i<10l$i++) {
echo 'My variable name is '.${'myarray_row'.$id}[$i+0];
echo 'My variable name is '.${'myarray_row'.$id}[$i+1];
echo 'My variable name is '.${'myarray_row'.$id}[$i+2];
echo 'My variable name is '.${'myarray_row'.$id}[$i+3];
}
However, its generally a good idea to not use them at all. making a multi-dimensional array instead would be much better for your case.
Question: if your $myarray_rowN has 4 elements why does your example have $i+X in the index?
surely it will go out of bounds after the first iteration :/ (1+1 OK, 1+2 OK, 1+3 OK 1+4 !OK etc)
possibly something like this might be better? (could be javascript though)
$index = 0;
$rows = array();
while (isset(${'myarray_row'.$i})) {
array_push($rows, ${'myarray_row'.$i});
}
foreach ($rows as $row) {
echo 'My variable name is '.$row[0]."\r\n";
echo 'My variable name is '.$row[1]."\r\n";
echo 'My variable name is '.$row[2]."\r\n";
echo 'My variable name is '.$row[3]."\r\n";
}
Sounds like you need to use a variable variable. See the docs here: http://php.net/manual/en/language.variables.variable.php
Something like this should work:
for ($i=0;$i<10;$i++) {
$var = 'myarray_row'.$i;
echo 'My variable name is ' . $$var[$i+0];
...
}
how about something like this:
foreach($myarray_row0 as $key => $value){
echo 'The ' . $key . ' value of this array is: ' . $value;
}
The above will iterate through all values in $myarray_row0 and echo the current value
I have a feeling I'm going to get scolded for this but here is the question.
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs['bullet_($seqnumber)'];?>
} // this one doesn't work.
I've tried
with curly brackets {}
I basically have a few columns that are named same except for number at the end (bullet_1, bullet_2, bullet_3, etc.) and want to get the results using a loop.
Your problem is, that PHP doesn't replace variables inside strings enclosed with single quotes. You need to use $db_rs["bullet_{$seq_number}"] or one of those:
<?php
foreach ($seq_numbers as $seq_number) {
$key = 'bullet_' . $seq_number;
echo $db_rs[$key];
}
Even shorter, but a little less clear:
<?php
foreach ($seq_numbers as $seq_number) {
echo $db_rs['bullet_' . $seq_number];
}
An entirely different approach would be to loop over the result array. Then you don't even need $seq_numbers. Just as an afterthought.
<?php
foreach ($db_rs as $key => $value) {
if (substr($key, 0, 7) == 'bullet_') {
echo $value;
}
}
Oh...and watch out for how you spell your variables. You are using $seq_number and $seqnumber.
<?php echo $db_rs['bullet_'.$seqnumber];?>
why not:
$db_rs['bullet_'.$seqnumber]
If not, what are your fields, and what does a var_dump of $db_rs look like?
try this...
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs["bullet_($seqnumber)"];?>
} // now it works.