How can I retrieve all of the values from variable arrays within a variable array?
EDIT: I most likely don't know how to explain it well, but I want to know how I can display the values in $oranges and $melon within $variables. I thought it would be as simple as setting variables and placing them into an array but it returns "Array".
Example:
<?php
$oranges = array("0","1");
$melon = array("2","3");
$variables = array($oranges,$melon);
$i = 1;
foreach ($variables as $var) {
$name = "txt".$i;
echo "<input type='text' name='".$name."' value='".$var."' />";
$i++;
echo "<input type='file' name='image'>";
}
?>
Retrieving values of an array within another equals to retrieve a value from one single array. You just have to know what you want to do.
Suppose we have array $A and array $A1 and $A2 inside $A. foreach ($A as $innerArray) ... $innerArray the first inner array for the first loop, then the second etc ... If you want to get $innerArray values, make another loop, or get them directly if you already know the keys.
Exemple :
here are your vars:
$oranges = array("0","1");
$melon = array("2","3");
$variables = array($oranges,$melon);
Retrieve value of single array
echo $oranges[0]; // prints 0
echo $melon[1]; // prints 3
Retrieve values from array within another
foreach ($variables as $var) {
$name = "txt".$i;
echo "<input type='text' name='".$name."' value='".$var["INDEX"]."' />"; // INDEX must be an existing key in $oranges or $melon
$i++;
echo "<input type='file' name='image'>";
}
According to your code
$oranges = array("zero","one");
$melon = array("two","three");
$variables = array($oranges,$melon);
$i = 1;
foreach ($variables as $var) {
// $var[0] will contain "zero"
// $var[1] will contain "one"
//When $i increments to 2 on the next loop
// $var[0] will contain "two"
// $var[1] will contain "three"
}
If you want to access these values without a loop, it is as simple as
$variables[0][0] ---> "zero"
$variables[0][1] ---> "one"
$variables[1][0] ---> "two"
$variables[1][1] ---> "three"
Related
I have an array called $alldata
If I do this
echo $alldata[0][6][0]["COLOUR"];
It successfully returns the colour. I want to access the value without using the name / label "COLOUR"
I tried this, but it fails with undefined offset
echo $alldata[0][6][0][0];
Re-index so you can use a numeric index:
echo array_values($alldata[0][6][0])[0];
Or for them all:
$result = array_values($alldata[0][6][0]);
echo $result[0];
echo $result[2];
You have to use foreach for this, since the array key is "COLOUR" and not 0.
here's an example on how to solve your problem.
<?php
$alldata = array(
0=>array(
6=>array(
0=>array(
"COLOR"=>"test"
))));
print_r($alldata);
foreach ($alldata[0][6][0] as $key => $value) {
echo $key . "=>" . $value;
}
?>
if you want to use the third key, then you can add a counter to it, by defining $x outside of the foreach and $x++; in the foreach.
I have an associative array of data coming from another script:
while($row = mysqli_fetch_assoc($query)){
$replyArray[] = array(
'did' => $row['discussion_id'],
'rid' => $row['reacter_id'],
'reply' => $row['reply'],
'date' => $row['date']
);
}
I have a function that will use this array $replyArray:
//In this function we extract data(discussions) from array
//This function is called inside disReply function.
function subDiscussion($replyArray){
$reply_count = count($replyArray);
for($x=0; $x < $reply_count; $x++){
echo "<br><h3>Data: ".($x +1).' <br>'."</h3>" ;
foreach($replyArray[$x] as $key => $value){
echo $data= $key.": ". $value."<br>";
}
}
};
The example above returns all associated paired data by just echoing the variable $data.
What I want to achieve is to separate the data(data in paire) into different variables:
$rid = its value
$did = its value
$reply = its value
$date = its value
The reason is because I want to put them in an HTML design in that function later.
Thank you.
Variable variables will help here:
// inside the final (foreach) loop
foreach($replyArray[$x] as $key => $value){
$$key = $value;
}
// now use these variables, $did, $rid, etc., e.g. save to an array or use in a function - else they will be overwritten in next iteration of parent for loop
Read more about variable variables here.
According to what Patrick Q suggested using the PHP extract()
for($x=0; $x < $reply_count; $x++){
extract($replyArray[$x]);
}
extract() This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable
Upon posting a form using _GET I would like to get the input name
See below part of url upon submit
.php?14=0&15=0&16=0&17=0&18=0&19=0
I know how to get the variable E.G:
$14=$_GET["14"];
Which is 0
However is it possible to do this and get the input name (eg 14) and then turn these into variables? (To save the input name to the DB)
To get all the $_GET parameters, you can do:
foreach($_GET as $key => $value){
echo "Key is $key and value is $value<br>";
}
This will output each key (14, 15, 16 etc) and value (0, 0, 0 etc).
To bind a variable name with a variable string, look at variable variables:
foreach($_GET as $key => $value){
$$key = $value;
}
As a result, you will have the following variables with the following values:
$14 = 0;
$15 = 0;
$16 = 0;
// etc...
Alternatively (as you don't necessarily know what the key/value pairs would be), you could create an empty array and add these keys and values to it:
foreach($_GET as $k => $v){
$arr[$k] = $v;
}
The resulting array will be:
$arr[14] = 0;
$arr[15] = 0;
$arr[16] = 0;
// etc...
Solution using single loop (Update):
If you're just using question/answer single time you can do it in single loop like this,
<?php
foreach($_GET as $key => $value){
$question = $key;
$answer = $value;
// Save question and answer accordingly.
}
If you will be using question answer to perform other things, use the following method.
You can get all the keys using array_keys(), where $_GET is an array.
Use it like this,
<?php
$keys=array_keys($_GET);
print_r($keys); // this will print all the keys
foreach($keys as $key) {
// access each key here with $key
}
Update:
You can make a pair of question,answer array and put it in the main array to insert it in the database like this,
<?php
$mainArray=array();
$keys=array_keys($_GET);
foreach($keys as $key) {
// access each key here with $key
$questionAnswerArray=array();
$questionAnswerArray["question"]=$key;
$questionAnswerArray["answer"]=$_GET[$key];
$mainArray[]=$questionAnswerArray;
}
// Now traverse this array to insert the data in database.
foreach($mainArray as $questionanswer) {
echo $questionanswer["question"]; //prints the question
echo $questionanswer["answer"]; // prints the answer.
}
I post a form with the same input names+id at the end like that:
<input type="text" name="machine_1">
<input type="text" name="machine_11">
<input type="text" name="machine_23">
How loop through on each of them and get the id's in the loop?
I tried this way, but it will loop a lot without any data and what happens if there is more thank 100 id?
for($i=0; $i<100; $i++){
$_POST["machine"]=$_POST["machine_".$i];
$id=$i;
}
POST is an associate array, so you can loop through everything that's been posted like this:
//$k contains the id
//$v contains the submitted value
foreach($_POST as $k => $v) {
//test if id contains 'machine'
if(stristr($k, 'machine')) {
echo $v;
}
}
You can do this using a foreach loop, like so:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value';
}
$_POST["machine"]=$_POST["machine_".$i];
here $_POST['machine'] represents noting..how can you assign a value to $_POST['machine']..you havent passed any element having name machine while submitting the form..so first of all you need to check it bro
In your code, you have:
$_POST["machine"]=$_POST["machine_".$i];
That's not the correct way. You want to store the value of $_POST["machine_".$i] to $id and then use it below.
This is probably what you need:
for($i=1; $i<100; $i++){
$id = $_POST["machine_".$i];
echo $id;
}
And if there are more than 100 elements, and you don't know the number of inputs, then you can use a foreach loop, as below:
$i = 1; // counter variable
foreach ($_POST as $key => $input) {
if($key == "machine_".$i) {
$id = $input; // or simply 'echo $input'
echo $id;
}
$i++; // increment counter
}
How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php