This code adds four instances of ${"v$i"} to my array, which when called just shows "duck" four times. Because of course $i at this point is 4. What I want to do is add the variable VALUES to my array, rather than the variable name. This way the first iteration would find variable v1, and add the value of "cat" to my array. And so on. How do I do this?
<?php
v1="cat";
v2="dog";
v3="turtle";
v4="duck";
$animals = array();
for ($i=1; $i<5; $i++) {
$animals[]=$ {"v$i"};
}
print_r ($animals);
?>
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 have a php array, and inside the array is a reference to another php object with a numerical value.
How can i access the elements in this array without knowing that numerical id (it could be different for each array)?
In the image below, I need to get the values inside field_collection_item like so....
$content['field_image_columns'][0]['entity']['field_collection_item'][133]['field_image']
For the first array key (0) i have done the following...
$i = 0;
while($i <= 2) {
if(isset($content['field_image_columns'][$i])) {
print '<div class="column-' . $i . '">';
foreach ($content['field_image_columns'][$i]['entity']['field_collection_item'] as $fcid => $values) {
// Print field values
}
print '</div>';
}
$i++;
}
Doing a foreach loop for a single array item seems wrong - is there a method i should be using for this use case?
You can select first item of array for example with:
Use array_shift, but it will modify source array:
$cur = array_shift($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
Get keys of array with array_keys and use first element of result as a key
$ks = array_keys($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $content['field_image_columns'][$i]['entity']['field_collection_item'][$ks[0]]['field_image'];
Use current function:
$cur = current($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
As with most programming, there are quite a few ways you could do it. If a foreach works, then it isn't wrong, but it may not be the best way.
// Get the current key from an array
$key = key($array);
If you don't need the key, then you can just get the value from the array.
// Get the current value from an array
$value = current($array);
Both of these will retrieve the first key/value from the array assuming you haven't advanced the pointer.
current, key, end, reset, next, & prev are all array functions that allow you to manipulate an array without knowing anything about the internals. http://php.net/manual/en/ref.array.php
$matrix=array($_SESSION['review_buffer_name'],$_SESSION['review_buffer_mail'],$_SESSION['review_buffer_comment']);
The above line of code is inside WHILE loop So that it stores more than one record of array.Is it correct way to store records?. And how can we access each record and value of matrix?
$matrix should store multiple row of arrays... The problem is when i'm accessing $matrix[2] then it is giving second value of array... instead of second record of array
You can try it:
//Before while loop declare the array variable
$matrix = array();
While(your condition){
$matrix[] = array(
$_SESSION['review_buffer_name'],
$_SESSION['review_buffer_mail'],
$_SESSION['review_buffer_comment']
);
}
//To access array:
print_r($matrix[0]); //print_r whole first row. (array start from 0)
echo $matrix[0][0]; //echo single data that first row's first data
Or you can set index as name like:
//Before while loop declare the array variable
$matrix = array();
While(your condition){
$matrix[] = array(
'review_buffer_name'=>$_SESSION['review_buffer_name'],
'review_buffer_mail'=>$_SESSION['review_buffer_mail'],
'review_buffer_comment'=>$_SESSION['review_buffer_comment']
);
}
//Then access array:
print_r($matrix[0]); //print_r whole first row. (array start from 0)
echo $matrix[0]['review_buffer_name']; // first row's first data
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++;
}
Im using wordpress as my base and I need to output the post meta for all my posts, but only for a certain number of keys.
What I intend to do is to save a list of all my keys, that im going to use to query wordpress for metadata for that post.
Below is my code.
//HERE YOU CAN SEE THE KEYS IMM USING ATM
$nyckellista[] = array("ebutik_allm_bas_operativsystem" ,"--foretagsform"
,"ebutik_allm_bas_omsättning");
$i = 0;
//Here im trying to query the get_post_meta with my keys and save the result (it's an array aof values that it return)
foreach($nyckellista as $nyckel)
{
$nyckellista[$i] = get_post_meta($post->ID,$nyckel,false);
echo $i . "Nyckel:" . $nyckel[$i];
$i++;
}
//HERE ME TRYING TO PRINT THE ARRAY CONTENTS
$count = count ($nyckellista);
echo $count;
for($y=1; $y <= $count; $y++)
{
$countmore=count($nyckellista[$y]);
for($x=1; $x <= $countmore; $x++)
{
print ($nyckellista[$y][$x] . "<br> ");
}
echo "<br>";
}
WHAT AM I DOING WRONG?
In the first line the $nyckellista variable is being declared implicitly as an array and then you're assigning to its first position an array of values.
Is this what you need/intend?
Edit:
Another point is, in the counts area of the code, that php arrays get numeric indexes starting at 0, not at 1 (see Example #4 in PHP array reference)