This question already has answers here:
How To Access Values In Associative Array Using PHP
(3 answers)
Closed 3 years ago.
How can I access the values that the associative array brings in "version" separately? I mean, I want to be able to bring v1, v2 and v3 separately to use them.
<?php
$version = array("v1", "v2", "v3");
$newarray = array("value1" => "Value 1",
"value2" => "Value 2",
"version" => implode($version));
I understand that with a foreach it is possible, but I do not know how. And on the other hand, I do not know if it's the best way to assign that array "version" with implode
Implode has no use in this example.
<?php
$version = array("v1", "v2", "v3");
$newarray = array("value1" => "Value 1",
"value2" => "Value 2",
"version" => $version);
echo '<pre>';
print_r($newarray);
echo '</pre>';
foreach ($newarray["version"] as $key => $value) {
print '<br /> key: ' . $key . ' value: ' . $value;
}
You can use foreach($key as $value), when $key equals "version" and do another "for loop" or when $value is type of array, do another "for loop".
Maybe if you look at your arrays in this way it will help :
$version['0'] = 'v1';
$version['1'] = 'v2';
$version['2'] = 'v3';
$newarray['value1'] = 'Value 1';
$newarray['value2'] = 'Value 2';
$newarray['version']['0'] = 'v1';
$newarray['version']['1'] = 'v2';
$newarray['version']['2'] = 'v3';
so to use foreach on version array , the one inside $newarray :
foreach ($newarray['version'] as $key=>$value) {
// Do something
}
Related
This question already has answers here:
Loop through associative array of associative arrays using foreach loop [closed]
(2 answers)
Closed 1 year ago.
I create an associative array in which there is an array, I want to print an associative array (key) and an array that is in it (value)
I have tried using a foreach but only managed to print the key but it shows an error for its value (Error: Array To String Conversion).
The second experiment, I tried using the foreach loop for the key and then used the loop for to print the value (Error: Undefined Offset).
<?PHP
$siswa = array(
"Kelas-X" => array("Joko", "Budi", "Duduk"),
"Kelas-XI" => array("Entong", "Timun", "Opang"),
"Kelas-XII" => array("Mamat", "Sadaw", "Koreng"),
);
foreach($siswa as $key => $value){
echo "Key : " . $key . "Value : " . $value;
}
?>
You cannot use echo on an array, you have to convert it to string before.
You can use json_encode for that.
Like this :
echo "Key : " . $key . "Value : " . json_encode($value);
Use two foreach loop
<?php
$siswa = array(
"Kelas-X" => array("Joko", "Budi", "Duduk"),
"Kelas-XI" => array("Entong", "Timun", "Opang"),
"Kelas-XII" => array("Mamat", "Sadaw", "Koreng"),
);
foreach($siswa as $key => $value){
foreach($value as $k => $v){
echo "Key : " . $key. "Value : " . $v;
}
}
?>
I can get the index number from a foreach loop by doing the following.
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// gives me "1: $row etc
}
If my array is associative is there away to get the associative name instead of the index number into my loop?
Actually you allready did it:
$associativeArray = array(
'First' => 1,
'Second' => 2,
'Third' => 3,
);
foreach ($associativeArray as $index => $value) {
echo $index . ": " . $value;
}
// First: 1
// Second: 2
// Third: 3
<?
$rows = array();
$rows['hi'] = 'there';
$rows['foo'] = 'bar';
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// $index will be hi and foo
}
?>
PHP arrays ARE associative where regular arrays just have integers as keys.
The PHP documentation actually mentions this in the first sentence: http://php.net/manual/en/language.types.array.php
An array in PHP is actually an ordered map..
PHP doesn't have arrays, it has maps/dictionaries that are called arrays but they are not arrays like in other languages.
I'm working with Simple HTML DOM like this:
foreach($html->find('img', 18) as $d) {
echo $d->outertext;
}
Now I want to implement an array of variables, in this case images, so I did:
$img=array(
"img"=>"18",
"img"=>"21"
);
foreach($img as $x=>$x_value)
{
$d = $html->find($x, $x_value);
echo $d->outertext;
}
The problem is that Simple HTML DOM is only returning the last image in array, which is number 21. What do I have to do to make it return everything in the array?
It's because both items in your $img array has the same key. foreach doesn't recognize them as two seperate items because both keys are img.
Example code to demonstrate:
$test = array(
"key" => 1,
"key" => 2
);
echo "Length of array: " . count($test) . "\n\n";
echo "Items in array:\n";
foreach($test as $key => $value) {
echo "$key => $value\n";
}
Outputs:
Length of array: 1
Items in array:
key => 2
I can only imagine that this is fairly simple, and yet the solution eludes me.
Let assume I have the following variables:
$group1 = "5";
$group2 = "1";
$group3 = "15";
$group4 = "3";
$group5 = "7";
$group6 = "1";
$group7 = "55";
$group8 = "0";
$group9 = "35";
I want the groups listed with the highest amount first e.g.:
Group 7 is number 1 with 55.
Group 9 is number 2 with 35.
Group 3 is number 3 with 15.
Group 5 is number 4 with 7.
Group 1 is number 5 with 5.
Group 4 is number 6 with 3.
Group 2 is number 7 with 1.
Group 6 is number 8 with 1.
Group 8 is number 9 with 0.
Perhaps it would be easier to list all the data in a double-array and then sort it?
First of all, use arrays(just usual arays).
If you array is
$group = array(1 => 5, 2 => 1 ... )
You may use arsort function.
Here I use numbers, not strings. If you will use strings (for values) you need a flag for sort (SORT_NUMERIC)
More information in PHP Manual
Then use foreach
foreach($group as $key => $value){
$key is number of varaiable
$value is value of it.
you also may add counter to print 1,2,3...
}
use arrays for this purpose
$group[1] = "5";
$group[2] = "1";
$group[3] = "15";
$group[4] = "3";
$group[5] = "7";
$group[6] = "1";
$group[7] = "55";
$group[8] = "0";
$group[9] = "35";
and then sort it.
arsort($group, SORT_NUMERIC); // SORT_NUMERIC suggested by **fab**
Just have your data inside an associative array, and sort it with an association aware sort:
$groups = array(
'group1' => "5",
'group2' => "1",
'group3' => "15",
'group4' => "3",
'group5' => "7",
'group6' => "1",
'group7' => "55",
'group8' => "0",
'group9' => "35",
);
arsort($groups);
// iteration as usual
foreach ($groups as $group_name => $value) {
}
// getting elements with the array functions based around the array's internal pointer
reset($groups); // reset the pointer to the start
print key($groups); // the first element's key
print current($groups); // the first element's value
next($groups); // moving the array to the next element
Yes using an array is the best thing to do.
something like that
$group[1]="5";
$group[2]="1";
After that you can sort your array
The best way to do this is with an array and arsort. This will keep your indexes intact.
arsort returns a boolean so do not assign to a new variable
$groups = array("5","1","15","3","7","1","55","0","35");
arsort($groups, SORT_NUMERIC);
$i = 1;
foreach ($groups as $key => $val) {
echo 'Group ' . $key . ' is number ' . $i . ' with ' . $val;
$i++;
}
Put your groups in an array
$groups = array("5","1","15","3","7","1","55","0","35");
arsort($groups); //This sort the array is descending order
var_dump($sorted_groups);
To print the array in your format use the following function
count = 1;
foreach($groups as $key => $value) {
echo "Group ".($key+1)." is number ".$count++." with ".$value;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
foreach with three variables add
If I have 3 arrays of the same size, is it possible to use the costruct foreach() to cycle in the same time the 3 arrays?
ex.
$name contains names
$surname contains surnames
$address contains addresses.
Can foreach take elements [1], [2], [.....] in the same time, to print
$name[1], $surname[1], $address[1];
$name[2], $surname[2], $address[2];
and so on?
SPL's multipleIterator is designed for precisely this purpose
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($array1));
$mi->attachIterator(new ArrayIterator($array2));
$mi->attachIterator(new ArrayIterator($array3));
foreach ( $mi as $value ) {
list($name, $surname, $address) = $value;
echo $name , ' => ' , $surname , ' => ' , $address , PHP_EOL;
}
Assuming they are all the same length:
for ($i = 0; $i < count($names); $i++) {
echo "{$names[$i]}, {$surnames[$i]}, {$addresses[$i]}";
}
You can do it like that (if arrays have the same keys):
foreach ($name as $key => $value) {
//use $name[$key], $surname[$key], $address[$key]
}
$key contains key in $name array
$value = $name[$key]
Try this
foreach($arr1 as $i => $val) {
var_dump($val, $arr2[$i], $arr3[$i]);
}
If the array keys are the same you can use key() function.
But you can pass the key to foreach($array as $key => value()){}
This way you can refer to the key by the variable without using a function.