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
Related
I want to get keys and values from a multi-dimensional array dynamically, to better explain what I'm trying to achieve please see the code below.
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $faq['faq1'][$i];
echo $faq['faq1_answer'][$i];
$i++;
}
The literal text above faq1 and faq1_answer needs to be replaced by the variable $q and $a respectively for me to be able to get the keys and values dynamically, but I cannot figure out how to add the variable.
The keys will always be the same, except for the number, which will change from 1 to 99. So with the code above, I can get the value of faq1 but I also need to grab the value of faq2 etc, hence why the variables above would work as I need.
tl;dr faq1 needs to be able to change to faq2 on the next iteration, hence the reason for me using $i.
Maybe like this?
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $f[$a];
echo $f[$a];
$i++;
}
I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}
I just started learning PHP and I am having some difficulties with some of the coding.
Hopefully, someone could help me a little.
I'm using this:
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1) {
echo " $a1";}}
The echo will write several results of $a1 depending on how many were selected in the form.
What I want is to save those results to some values so I can add them in MySQL.
Something like this:
if(!empty($_POST['yyy']))
{
foreach($_POST['yyy'] as $a1)
{
echo " $a1"; where $a1 will create a $result1,$result2,$result3(for each isset)
}
}
Then if I use:
echo "$result2";
it will give me the second result.
Not clear whether you are asking about this kind of result or not. But you can use an array to store each values inside the foreach loop.
var data=[];// define an array to access outside of if statement later..
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1){
data[]=$a1;
//or can use array_push() method
array_push(data,$a1);
}
}
/*this will give the second result(because array indexing starts from 0. So to get third result
use data[2])*/
echo data[1];
Furthermore by echoing quoted variable will not give the value of that variable but gives a string literal.
echo "$result2" //output---> $result
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.
When sending data from a form to a second page, the value of the session is always with the name "Array" insteed of the expected number.
The data should get displayed in a table, but insteed of example 1, 2, 3 , 4 i get : Array, Array, Array.
(A 2-Dimensional Table is used)
Is the following code below a proper way to "call" upon the stored values on the 2nd page from the array ?
$test1 = $_SESSION["table"][0];
$test2 = $_SESSION["table"][1];
$test3 = $_SESSION["table"][2];
$test4 = $_SESSION["table"][3];
$test5 = $_SESSION["table"][4];
What exactly is this, and how can i fix this?
Is it some sort of override that needs to happen?
Best Regards.
You don't need any sort of override. The script is printing "Array" rather than a value, because you're trying to print to the screen a whole array, rather than a value within an array for example:
$some_array = array('0','1','2','3');
echo $some_array; //this will print out "Array"
echo $some_array[0]; //this will print "0"
print_r($some_array); //this will list all values within the array. Try it out!
print_r() is not useful for production code, because its ugly; however, for testing purposes it can keep you from pulling your hair out over nested arrays.
It's perfectly fine to access elements in your array by index: $some_array[2]
if you want it in a table you might do something like this:
<table>
<tr>
for($i = 0 ; $i < count($some_array) ; $i++) {
echo '<td>'.$some_array[$i].'</td>';
}
</tr>
</table>
As noted, try
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
That should show you what's in the session array.
A 2-dimensional table is just an array of arrays.
So, by pulling out $_SESSION["table"][0], you're pulling out an array that represents the first row of the table.
If you want a specific value from that table, you need to pass the second index, too. i.e. $_SESSION["table"][0][0]
Or you could just be lazy and do $table = $_SESSION["table"]; at which point $table would be your normal table again.
A nice way ...
<?php
foreach ($_SESSION as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>