I am currently learning PHP and I am stuck with this problem while testing foreach with multi-dimensional arrays.
Here is my array:
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
Whenever I try to output I always get an error of Array to string conversion or Invalid argument. Can somebody tell me how could I correctly output this multi-dimensional array using foreach?
If I do it this way, the data like 125,000, basically the value assigned to age and salary isn't written out.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
If I do it this way, then it writes out, but as well it writes out "Array" and array to string error:
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
echo $specifics.$values.'<br>';
}
foreach($values as $hobbies) {
echo $hobbies;
}
}
Thanks.
Try following code
<?php
$employees = array(
'Josh' => array(
'age'=>'55',
'salary'=>'105,000',
'hobbies'=> array('none')
),
'John' => array(
'age'=>'45',
'salary'=>'125,000',
'color'=>'red',
'hobbies'=> array('none')
),
'Jane' => array (
'age'=>'25',
'salary'=>'93,000',
'hobbies'=> array ('fishing', 'flying')
)
);
foreach( $employees as $names_of_employees => $data ){
echo $names_of_employees.'<br>';
echo "Salary: ".$data['salary'].'<br>';
echo "Age: ".$data['age'].'<br>';
if( isset($data['hobbies']) && !empty($data['hobbies']) ) {
echo "Hobbies: ";
foreach( $data['hobbies'] as $hobbies ) {
echo $hobbies.'<br>';
}
}
}
Well, it depends on what you want.
foreach( $employees as $name => $data ){
echo $name;
echo $data['age'];
echo $data['salary'];
// ...etc...
}
It looks like for array element 'John' you've got an extra item in the second dimension. I believe this is ok in PHP but perhaps you have to account for this in the code you use to read the values out.
It is because you are trying to convert an array to a string. The problem is caused by hobbies since it is an array. So in your foreach loop that goes through $data you need to check if it is an array or if the key is equal to hobbies.
foreach($employees as $names_of_employees=>$data) {
echo $names_of_employees.'<br>';
foreach($data as $specifics=>$values) {
if(is_array($values)) { //or you could say if($specifics == 'hobbies')
echo $specifics . ': ' . implode(',',$values) . '<br>';
} else {
echo $specifics . ': ' . $values . '<br>';
}
}
}
Related
$studentArray = array(
array("ahmed2",15,3.5),
array("ahmed1",15,2.4),
array("ahmed3",29,3.9),
array("ahmed4",22,3),
array("ahmed5",23,2.8)
);
foreach($studentArray as $key => $value ){
echo $key. '-'.$value.'<br>';
}
Since you have student detail array in $studentArray, you need an extra foreach to loop through inner array.
Try below code in your structure.
$studentArray = array(
array("ahmed2",15,3.5),
array("ahmed1",15,2.4),
array("ahmed3",29,3.9),
array("ahmed4",22,3),
array("ahmed5",23,2.8)
);
foreach($studentArray as $studentDetail ){
foreach($studentDetail as $key => $value ){
echo $key. '-'.$value.'<br>';
}
}
For more better understanding, have a try with below code.
$studentArray = array(
array("val1"=>"ahmed2","val2"=>15,"val3"=>3.5),
array("val1"=>"ahmed1","val2"=>15,"val3"=>2.4),
array("val1"=>"ahmed3","val2"=>29,"val3"=>3.9),
array("val1"=>"ahmed4","val2"=>22,"val3"=>3),
array("val1"=>"ahmed5","val2"=>23,"val3"=>2.8)
);
foreach($studentArray as $student){
foreach($student as $key => $value) {
echo $key. '-'.$value.'<br>';
}
echo '<br>';
}
I've got this array:
Array
(
[0] => Array
(
[name] => System
[order] => 1
[icon] => stats.svg
[0] => Array
(
[title] => Multilingual
)
[1] => Array
(
[title] => Coloring
)
[2] => Array
(
[title] => Team work
)
[3] => Array
(
[title] => Tutorials
)
)
)
I want to loop into this to show the section name and after all the features containing in the following array.
So, this is what I made:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
foreach (array_values($info) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
It works except for the first third <li> where I have the first char of name, order and icon value.
Do you know why ?
Thanks.
array_values return value of array so for info values is name, order, icon, 0, 1, ...
Your values foreach is wrong if you just want print title you can use:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
//Remove some keys from info array
$removeKeys = array('name', 'order', 'icon');
$arr = $info;
foreach($removeKeys as $key) {
unset($arr[$key]);
}
foreach (array_values($arr) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
In php, array_values means all the values of the array. So array_values($info) is array($info['name'], $info['order'], $info['icon'], $info[0], $info[1], $info[2], $info[3])
in your example, you can skip the non-integer keys of the $info to get your titles:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info[] = array('title'=>'Multilingual');
$info[] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info as $k => $item) {
if(!is_int($k)) continue;
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
BUT, your original data structure is not well designed and hard to use. For a better design, you can consider the following code, move your items to a sub array of $info:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info['items'] = array();
$info['items'][] = array('title'=>'Multilingual');
$info['items'][] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info['items'] as $item) {
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
Sample output of the two demos:
System
<ul class="menu-vertical bullets">
<li>Multilingual</li>
<li>Coloring</li>
</ul>
It works except for the first third li where I have the first char of name, order and icon value. Do you know why ?
Why you see first chars of the values of 'name', 'order', 'icon'? Let see how PHP works.
Take the first loop as an example: foreach (array_values($info) as $i => $key)
Then $i == 0, $key == 'System'
We know that $key[0] == 'S', $key[1] == 'y', $key[2] == 's', etc.
Then you try to access $key['title'], but the string 'title' is not valid as a string offset, so it is converted to an integer by PHP: intval('title') == 0.
Then $key['title'] == $key[intval('title')] == 'S'
That's what you see.
array_value() returns the values of the array, here you will get the value of the array $info and what I understand is that is not what you need. See details for array_value().
You can check if the key for the $info is an integer. if yes, echo the title. Give this a try.
foreach ($features as $feature => $info) {
echo $info['name'].'<ul class="menu-vertical bullets">';
foreach ($info as $key => $value) {
if (is_int($key)) {
echo '<li>'.$key['title'].'</li>';
}
}
echo '</ul>';
}
I have this name="opt['.$id.']" value="'.$points.'" inside a checkbox input.Does anybody knows how I can get the $id?
UPDATED:
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
But I don't get any value on echo..
You need to iterate over the HTML array. Something like this should do it for you:
foreach($_POST['opt'] as $id => $value) {
Demo: https://eval.in/585379
your used array so you need to Iterate the $_POST['opt'] value
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
foreach($_POST['opt'] as $id => $value)
{
echo $id //key example 1
echo $value //value example 100
}
If your $_POST is like this
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
and you are giving $_POST['opt'] to foreach then your array for foreach is
$_POST['opt'] = array('1'=>100);
then you can't use implode in foreach because it give you an error. Do it without implode.
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
echo $gift_ids;
}
I'm try to using array in PHP by finding it index and keys as foreach.
example I want to get $k["ab"] or $ro["hh"] but I can't get it
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
var_dump($k);
}
?>
You'd better learn the structure of multi-dimensional array.
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $key => $values){
echo $key; // which will output "test", "ab", which are the array keys
print_r($values); // which will output the contents of the inner array (e.g. array("some"=>"d","hello"=>"e","ther"=>"a") )
// to obtain the inner array values, you can either use another foreach...
foreach($values as $k => $v) {
echo $k . ', ' . $v; // which will output "ad, tt", etc
}
// ...or specify which key to obtain
if(isset($values["ad"])) { echo $values["ad"]; }
// isset() must be used, as the key does not exist in 1st inner array
}
?>
Please try Below :
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
if($k == "ab"){
echo "<pre>";
print_R($ro);
echo 'HH Value ===> '.$ro['hh'];
}
}
?>
And Want to get All values and Keys Try Below For Each :
foreach($data as $k=>$ro){
foreach($ro as $inner_key => $inner_value){
echo "<br/> Key ===> ".$inner_key."==== value =====>".$inner_value;
}
}
Hi I have an array like this:
array(
'Home' => array(
'About',
'Contact'
),
'News'
);
I wrote this to printing them:
function show($arr){
foreach($arr as $key => $value){
echo "\n<ul>\n<li>\n" . $key;
if( ! empty($value)){
if(is_array($value)){
show($value);
}else{
echo $value;
}
}
echo "\n</li>\n</ul>\n";
}
}
My problem is when I try to echo $value It'll print something like this:
Home
0About
1Contact
0News
I tried to echo $key where the echo $value is here now and I understood it's the key index which is gonna write before the News field or any field that is not an array. I fixed it with turning the single fields to this:
array(
'Home' => array(
'About' => **array()**,
'Contact' => **array()**
),
'News' => **array()**
);
But I don't want to define additional empty arrays!
Peace Out!
function show($arr){
foreach($arr as $key => $value){
echo "\n<ul>\n<li>";
if( ! empty($value)){
if(is_array($value)){
echo '\n'.$key;
show($value);
}else{
echo $value;
}
}
echo "\n</li>\n</ul>\n";
} }
I would say you have to change the place of you echo (of the $key). If it's not an array, you don't care about the key, right ?
function show($arr){
foreach($arr as $key => $value){
if (is_numeric($key))
echo "\n<ul>\n<li>\n";
else
echo "\n<ul>\n<li>\n" . $key;
if( ! empty($value)){
if(is_array($value)){
show($value);
}else{
echo $value;
}
}
echo "\n</li>\n</ul>\n";
}
}
I guess is_numeric should solve your problem.