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++;
}
Related
Lets say I have an array looking like this:
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30)
and a loop looking like this:
for($i=0;$i<count($sql);$i++){
$value[$i] = ($sql[$i]);
echo $value[$i];
}
I want the loop to iterate through the array and assign each value to a new variable.
In this code i tried to make it store the values in:
value1
value2
value3
But sadly this doesnt work, thus I am here seeking help.
Or is it a problem that i got an associative array instead of a numeric one?
I dont want to use this loop on this array only but on other arrays with different keys and length aswell.
Edit: I think I may have not wrote it cleary enough to tell you what i want to achieve:
I want to have three string values at the end of the loop not stored in an array:
Variable1 should contain "Peter"
Variable2 should contain "1"
Variable3 should contain "30"
Plus I want this loop to be dynamic, not only accepting this specific array but if I were to give it an array with 100 Values, I would want to have 100 different variables in which the values are stored.
Sorry for not being clear enough, I am still new at stackoverflow.
Going by your condition, assign each value to a new variable, I think what you want would be to use Variable variables. Here is an example:
<?php
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$count = 1;
foreach ($sql as $value) {
$x = 'value'.$count;
$$x = $value; //here's the usage of Variable variables
$count++;
}
echo $value1.'<br/>';
echo $value2.'<br/>';
echo $value3.'<br/>';
I went to your sample variables ($value1, $value2, etc.). I also changed your loop to foreach to easily loop the array. And I also added a $count that will serve as the number of the $value variable.
The $count wouldn't be necessary if your index are numeric, but since its an associative array, something like this is needed to differentiate the variables created
A brief explanation as requested:
$x contains the name of the variable you want to create (in this case, value1), then when you add another $ to $x (which becomes $$x), you are assigning value to the current value of $x (this equals to $value1='Peter')
To dynamically define a variable use $$. Demo
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$index = 1;
foreach($sql as $value){
${"value" . $index++} = $value;
}
I will be getting some certain amount of data. I will get the number for which the for loop to be run.
For example
I get the number 3 and I will get three parameters like par1,par2 and par3 then how should I pass this par1 in the $_post
like
$i=$_POST["number"];
for($i=1;$i<=$n;$i++)
{
$par.$i = $_POST["par".$i];
}
Here I cant get the value from $_POST["par".$i];
As it is not able to get the variable inside the paramater of $_POST
Any help will be thankful
I suggest that you create a new array $par and there you will put by index all the par you will have like this:
$i=$_POST["number"];
$par = [];
for($i=1;$i<=$n;$i++)
{
$par[$i] = $_POST["par".$i];
}
After that if you want to go throw all pars you can simply use foreach like this:
foreach($par as $key => $value) {
// $key will be 1,2,3
// $value will be the value from $_POST["par" . $i]
}
The . is to concatenate two strings in PHP, and you can't create a new variable like you tried. If you want to have in $par1, $par2 and $par3 you can do like this:
${"par" . $i} = $_POST["par".$i];
But I don't recommend this way because it's more hard to handle.
One Way
According to your question.
<?php
$n = $_POST["number"];
$par = "par";
for($i=1; $i<=$n; $i++){
$par.$i = $_POST["par".$i];
}?>
Alternative Way
In this scenario,
For example I get the number 3 and I will get three parameters like
par1,par2 and par3 then how should I pass this par1 in the $_post.
Better, make 'par' input name as an array type as 'par[]' (<input type='text' name='par[]'>) in your file instead using par1, par2 .. par(n).
And, no need to worry in submit page.
<?php
$n = $_POST["number"];
for($i=1;$i<= $n;$i++){
$newPar = $_POST["par"][$i];
// Write here your logic to use how you want.
}
?>
in this foreach loop, i put a function returning the room quantity, each $sumqty['room_qty'] has different value, my question is, i want to get the highest value of $sumqty['room_qty'], do i put it in an array? how? any help will be appreciated.
<?php
foreach($reservation as $res){
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
$sumqty['room_qty'];
}
$highest = ???;
?>
i want to display the highest value by echo $highest
Yes, you can use an array. Provided $sumqty['room_qty'] is a numeric value the following will work:
$allquantities=array();
foreach($reservation as $res){
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
$allquantities[]=$sumqty['room_qty'];
}
$highest = max($allquantities);
Assuming that sumqty takes an 'arrival', 'departure' and 'room id' and returns an array with key 'room_qty' mapped to some integer:
<?php
$highest = -1000000000; //some really, really small number
foreach ($reservation as $res) {
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
if ($sumqty['room_qty'] > $highest) {
$highest = $sumqty['room_qty'];
}
}
echo $highest;
The general idea is that each time you find a higher value, you replace the previously highest value with the new higher value.
No extra array is necessary to accomplish this! Solutions that use an array to solve this problem are unnecessarily complicated. (edit: "complicated" is a poor choice of words; if an extra array is used than the program is slightly less efficient)
Get an array of all the values of $sumqty['room_qty'], $room_qty[] as in this case.
<?php
$room_qty = array();
foreach($reservation as $res){
$sumqty = sumqty($res['arrival'],$res['departure'],$res['room_id']);
$room_qty[] = $sumqty['room_qty'];
}
$highest = max($room_qty);
?>
Once you have the array you could use max() function to find the maximum value in the given array. Go through this manual you will get be clear about it.
I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped
I want to create a array with values:
3,2,1.... and I want to use array_push and a forloop.
I have written the following code is not working..
============
<?PHP
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$temp4=1;
$temp5=1;
$arraytemp=array();
for($i=0;$i<4;$i++)
{
$r="temp";
$dd=$r.$i;
array_push($arraytemp,$dd);
}
echo $arraytemp[3];
?>
can you please let me know what I am missing
This is how should you assign $dd
for($i=0;$i<4;$i++)
{
$dd=${"temp".$i};
array_push($arraytemp,$dd);
}
your $dd has the name of your var as a string. you want to use this for this technique:
array_push($arraytemp,$$dd);
Pay attention to the double $$ :)
What happens here is the following: the $dd gets replaced by the string it contains. so your call
array_push($arraytemp,$dd);
will do this:
array_push($arraytemp,'temp0');
But you want this:
array_push($arraytemp,$temp0);
so you need to show you want an acutal $var with that name, so you add the $. It's just the way the syntax works, neccessairy to distinguish between a normal string and a string that's supposed to be a variable
confusing what do you want to achieve here, do you want to:
create array with value: temp0, temp1, temp2 ...
for($i=0;$i<4;$i++){
array_push($array,"temp{$i}");
}
echo $array[3];
create array with value: 0, 1, 2, 3 ..
for($i=0;$i<4;$i++){
array_push($array,$i);
}
echo $array[3];
create array with value based on your defined variable above ($temp0, $temp1 ...)
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$array = array();
for($i=0;$i<4;$i++){
$val = "temp{$i}";
array_push($array,$$val);
}
echo $array[3];
Easiest way, going by what you're requesting, although you didn't specify how many numbers you wanted to add. so for loop won't work that way. you're best off with a while loop.
$foo = array();
$i = 1;
while (some end condition) {
array_push($foo, $i);
$i++;
}
print_r($foo);