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);
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 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 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 theming a drupal content type, and I have a set of similarly named variables. e.g. field_anp_1, field_anp_2,..., field_anp_10. I want to dynamically print them out from within a for loop. Normally, one would print the values out individually by doing something like:
print $field_anp_1[0]['value'];
in my case, I can't do this because the last number changes. So, within a for loop, how would one print out these fields? I tried variable variables, but I don't seem to understand exactly what is going on there - and I don't think it likes the fact that this in an array. Any help would be greatly appreciated!
Definitely not an array. But you can use a variable as the name of a variable with {..}
ghoti#pc:~ $ cat invar.php
#!/usr/local/bin/php
<?php
$field_anp_3="three";
$field_anp_2="two";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (isset(${$thisvar})) {
printf("%s: %s\n", $i, ${$thisvar});
} else {
printf("%s: not set\n", $i);
}
}
ghoti#pc:~ $ ./invar.php
1: not set
2: two
3: three
4: not set
Alternately, if you are sure that the variables that do exist will be sequential. you can stop on failure (per comments below):
#!/usr/local/bin/php
<?php
$field_anp_1="one";
$field_anp_2="two";
$field_anp_3="three";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (!isset(${$thisvar})) {
break;
}
printf("%s: %s\n", $i, ${$thisvar});
}
I can see no reason for having an untold number of variables generated like that. But this is how you could collect them:
$vars = array();
foreach(get_defined_vars() as $name => $value) {
if(strpos($name, 'field_anp_') === 0) {
$vars[$name] = $value;
}
}
Now you would have your values as an associative array in $vars. Instead of adding the values to $vars, you could print them directly.
Update In response to your comment
$array = array('foo' => 'bar');
$x = 'foo';
$field_anp_bar = 'baz';
echo ${'field_anp_' . $array[$x]};
Ok, I figured it out. I simply needed to be more specific with PHP. To call a variable such as: $field_anp_0[0]['value'] from within a for loop, where 0 is increasing, one simply needs to do the following:
<?php
$numbers = array(123,235,12332,2342);
for($i; $i<count($numbers); $i++){
$var = "field_anp_".$numbers[$i];
printf("%s\n", ${$var}[0]['value']);
}
?>
This will allow me to list the fields that I will need to have printed out in the order I need to have them printed out. Then, I can use a for loop to print out a themed table for instance.
Thank you for the help!
I have the following code:
print $node->field_carousel_1[0]['filepath'];
What i would like to do is change the 1 and use a variable instead.
Do you have any idea how i would be able to do this?
What i am aiming for: Using a variable instead of the one to create a looping function to print field_carousel_1, field_carousel_2, field_carousel_3 etc
You can try something like this:
for ($i=1; $i<4; $i++) {
$field = "field_carousel_$i";
$arr = $node->$field;
print $arr[0]['filepath'];
}
I would store these in an array.
field_carousel=array('value1', 'value2', 'value3', 'etc.')
To print them, you would do...
foreach(field_carousel as $item) {
echo $item
}