How i can print Arrays with for each loop - php

<?php
$students = array(
"student1" => array(
"age" => 36,
"gender" => "male",
"qualification" => "Master",
),
"student2" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student3" => array(
"age" => 26,
"gender" => "male",
"qualification" => "BA",
),
"student4" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student5" => array(
"age" => 20,
"gender" => "male",
"qualification" => "Master",
),
"student6" => array(
"age" => 20,
"gender" => "male",
"qualification" => "F.A",
),
);
?>
And i need result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master.
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA.
I have try like this.
foreach($students as $key=>$value)
{
echo "Mr".$key."<br />";
foreach($value as $key=>$value)
{
echo" Your $key is $value and <br />";
}
}
And my result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master and
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA and

No need for that other foreach inside, you can just use one. Each copy of the sub array ($info), you will just have to call its indices.
foreach ($students as $name => $info) {
echo "
Hello $name, <br/>
Your age is: $info[age] <br/>
Your gender is: $info[gender] <br/>
Your qualification is: $info[qualification] <hr/>
";
}
But if you really want to go that two foreach route, yes you could add a condition in the second loop to prevent it from adding the superfluous and:
foreach ($students as $name => $info) {
echo "Hello $name ";
foreach($info as $att => $val) {
echo "Your $att is: $val ", (end($info) != $val) ? ' and ' : '<br/>';
}
}

Try with -
foreach($students as $key=>$value)
{
echo "Mr".$key."";
$count = 1;
foreach($value as $key=>$val)
{
echo" Your $key is $val";
if ($count != count($val)) {
echo " and ";
}
}
}

Try this code:
foreach($students as $key => $value) {
echo 'Hello ', $key, ' Your age is ', $value['age'], ' gender is ' . $value['gender'], ' and Your qualification is ', $value['qualification']
}
You can concat string with echo, but coma will be better for performance.

Related

Using Foreach to echo array in an array

I want to echo each persona included in the array $personas.
The following code echoes the first persona but it doesn't breaks the line and displays the second ("Mike").
Any help is much appreciated :)
<?php
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
foreach ( $person as $inner_param => $inner_value ) {
echo $param . ": " . $value . "<br>";
}
};
?>
Desired result:
Name: John | Age: 30 | Nationality: Spain |
Name: Mike | Age: 45 | Nationality: Peru |
Try this;
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
$text = "";
foreach ( $persona as $key => $val ) {
$text .= $key . ": " . $val . ' | ';
}
echo $text .'<br>';
}
I believe that I fixed it. Should it be as follows? Any better option?
foreach ($personas as $persona ) {
echo "<br>";
foreach ( $persona as $param => $value ) {
echo $param . ": " . $value . " | ";
}
};

Table list to be dynamic require with skip approach using multi arrays

I want to be build logic as with below desired result. I have multi arrays which to be listed in table as questionnaire along with skip approach.
Helps are definitely appreciated
Fiddle link also mentioned it :- http://phpfiddle.org/main/code/1sr6-kn5u
<?php
$users = array (
0 => array("user_id" => "217", "user_name" => "S", "id" => "33"),
1 => array("user_id" => "216", "user_name" => "A", "id" => "32"),
2 => array("user_id" => "215", "user_name" => "B", "id" => "31"),
);
$questions = array (
0 => array("text" => "Q1", "type" => "text", "qid" => "1"),
1 => array("text" => "Q2", "type" => "text", "qid" => "2"),
2 => array("text" => "Q3", "type" => "text", "qid" => "3"),
);
$answers = array (
0 => array("SRI" => "31", "qid" => "1", "answer" => "A1"),
1 => array("SRI" => "31", "qid" => "2", "answer" => "A2"),
2 => array("SRI" => "31", "qid" => "3", "answer" => "A3"),
3 => array("SRI" => "32", "qid" => "3", "answer" => "A3"),
4 => array("SRI" => "32", "qid" => "2", "answer" => "A2"),
5 => array("SRI" => "33", "qid" => "1", "answer" => "A1"),
6 => array("SRI" => "33", "qid" => "3", "answer" => "A3")
);
//echo "<pre>";
//print_r($users);
//print_r($questions);
//print_r($answers);
?>
<table border = 1>
<tr>
<th>
User
</th>
<?php
foreach($questions as $key => $Qval){
echo "<th>".$Qval['text']."</th>";
}
?>
</tr>
<?php
foreach($users as $key => $Uval){
echo "<tr>";
echo "<td>".$Uval['user_name']."</d>";
foreach($questions as $key => $Qval){
foreach($answers as $key => $Aval){
if (($Qval['qid'] == $Aval['qid']) && ($Uval['id'] == $Aval['SRI'])){
echo "<th>".$Aval['answer']."</th>";
}
}
}
echo "</tr>";
}
?>
</table>
Desired Result
You need to divise your problem in two steps :
detect if the user answer the current question or not
then display the result
foreach($users as $key => $Uval){
echo "<tr>";
echo "<td>".$Uval['user_name']."</d>";
foreach($questions as $key => $Qval){
$userAnswer = null ; // no user answer per default
foreach($answers as $key => $Aval){ // loop to find a user answer
if (($Qval['qid'] == $Aval['qid']) && ($Uval['id'] == $Aval['SRI'])){
$userAnswer = $Aval['answer']; // save the user answer
break ; // we found the user answer, no need to continue to loop over the remaining answers
}
}
// display the user answer, use a placeholder if none is found
echo '<td>' . (is_null($userAnswer) ? 'SKIP' : $userAnswer) . '</td>' ;
}
echo "</tr>";
}

cartesian product with PHP (id, name, variants)

Can you help me with generating caresian product.
It is similar to this stackoverflow. I want generate inputs so I need keep ID.
Example:
my input data:
[
1 => [
id => 1,
name => "Color",
options => [
5 => [
id => 5,
name => "Red"
],
6 => [
id => 6,
name => "Blue"
]
]
],
2 => [
id => 2,
name => "Size",
options => [
7 => [
id => 7,
name => "S"
],
8 => [
id => 8,
name => "M"
]
]
],
// etc
]
result I expect:
[
"5-7" => "Red / S",
"5-8" => "Red / M",
"6-7" => "Blue / S",
"6-8" => "Blue / M"
]
I need generic function for any number of properties/options..
Nested loop man, each entry of array 1 has to be linked with every entry of array2.
$finalArray = array();
foreach (array1 as $key1 as $value1){
foreach (array2 as $key2 as$value2){
echo $value1 . " - " .$value2."<br/>";
$finalArray[$key1.'-'.$key2] = $value1 ." - ".$value2;
}
}
the finalArray will be having what you need.
That is actually working code for now but don't know how much is efficient.
// filter out properties without options
$withOptions = array_filter($properties, function($property) {
return count($property['options']) > 0;
});
$result = [];
$skipFirst = true;
foreach ($withOptions as $property) {
if ($skipFirst) {
foreach (reset($withOptions)['options'] as $id => $option) {
$result[$id] = $option['name'];
}
$skipFirst = false;
continue;
}
foreach ($result as $code => $variant) {
foreach ($property['options'] as $id => $option) {
$new = $code . "-" . $id;
$result[$new] = $variant . " / " . $option['name'];
unset($result[$code]);
}
}
}

Loop array content value consist of single value and array

I have tried to loop this array but I still get error
I have an array like this:
1 => ["name"=>"A", "related"=>[
["signal"=>"A1", "color"=>"green"],
["signal"=>"A2", "color"=>"lime"],
["signal"=>"A3","color"=>"yellowGreen"]
]]
2 => ["name"=>"B", "related"=>[
["signal"=>"B1", "color"=>"Red"],
["signal"=>"B2", "color"=>"Pink"]
]]
How to display as - A : Green, lime, yellowGreeb
- B : Red, Pink
This is my code that I've tried to display as above format
foreach($arr as $key => $value){
echo $value["name"];
foreach($value["related"] as $k){
echo $k["color"] . ",";
}
}
It throw error this array dont has $value["related"] index. But It can echo the $value["name"]???
Thank you!
Find the solution as below:
$array = [1 => [
"name" => "A",
"related" => [
["signal" => "A1", "color" => "green"],
["signal" => "A2", "color" => "lime"],
["signal" => "A3", "color" => "yellowGreen"]
]
],
2 => ["name" => "B", "related" => [
["signal" => "B1", "color" => "Red"],
["signal" => "B2", "color" => "Pink"]
]]
];
foreach ($array as $ar) {
$new_arr = array_column($ar['related'], 'color');
$required_string = implode(', ', $new_arr);
echo $ar['name'].' : ' .$required_string;
echo "<br />";
}
For PHP Version < 5.5 you can use below solution:
foreach ($array as $ar) {
$new_arr = array_map(function ($value) {
return $value['color'];
}, $ar['related']);
$required_string = implode(', ', $new_arr);
echo $ar['name'].' : ' .$required_string;
echo "<br />";
}
you can found more detail about foreach loop at http://php.net/manual/en/control-structures.foreach.php

Empty arrays error

i have a set of php arrays, and i am trying to retrieve those details and echo. however i get errors such as Warning: Invalid argument supplied for foreach().
how can i rectify such errors from appearing?
this problem occurs when i echo all cakes from all users.
I have tried so far to eliminate possible errors from the code and also used validation statements such as if empty then do this, however the problem still persists.
<?php
//USERS ARRAYS
$users = array();
$users["john"] = array(
"first name" => "John",
"last name" => "Smith",
"address" => "London");
$users["jade"] = array(
"first name" => "Jade",
"last name" => "Anthony",
"address" => "Essex");
$users["clement"] = array(
"first name" => "Clement",
"last name" => "Smith",
"address" => "Essex");
//CAKES ARRAY
$cakes = array();
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
),
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes")),
"clement" => NULL,
);
?>
<?php $user_name = 'john';?>
<h1>Name</h1>
<p><?php echo $users["first name"]; ?></p>
<h1>Cakes Made</h1>
<?php
foreach($cakes[$user_name] as $key => $val)
{ echo $key . " <strong>Ingredients: </strong>" . $val["ingredients"] . "<br>"; }
?>
<h1>All cakes from all users</h1>
<?php foreach($cakes as $cake) { ?>
<?php if(is_array($cake)) {
foreach($cake as $cakemade => $newval)
if(empty($cakemade)) { echo "";} else
{ echo $cakemade . "<strong>" . $newval['ingredients'] ."</strong> <br>"; }
?>
<?php }} ?>
your input is welcome. :)
edit: Just to be clear the code error relates to the second part of the code in which it displays all cakes from all users.
You can test if the variable in want use in foreach is set
if(isset($cakes[$user_name]) && count($cakes[$user_name]) > 0)
foreach($cakes[$user_name] as $key => $val) {}
Missing "s for the keys.Your array should be -
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
)
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes"),
"clement" => NULL,
);
if(is_array($variable) && count($variable) > 0) {
foreach($variable as $key => $value) {
//Your code
}
)
You have many syntax errors in your pasted code. also use is_array() to check an array.
also you have defined $username = "john" and passing in foreach with $user_name
try
<?php
//USERS ARRAYS
$users = array();
$users["john"] = array(
"first name" => "John",
"last name" => "Smith",
"address" => "London");
$users["jade"] = array(
"first name" => "Jade",
"last name" => "Anthony",
"address" => "Essex");
$users["clement"] = array(
"first name" => "Clement",
"last name" => "Smith",
"address" => "Essex");
//CAKES ARRAY
$cakes = array();
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
),
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes")),
"clement" => NULL,
);
?>
<?php $user_name = 'john';?>
<h1>Name</h1>
<p><?php echo $users["first name"]; ?></p>
<h1>Cakes Made</h1>
<?php
foreach($cakes[$user_name] as $key => $val)
{ echo $key . " <strong>Ingredients: </strong>" . $val["ingredients"] . "<br>"; }
?>
<h1>All cakes from all users</h1>
<?php foreach($cakes as $cake) { ?>
<?php if(is_array($cake)) {
foreach($cake as $cakemade => $newval)
if(empty($cakemade)) { echo "";} else
{ echo $cakemade . "<strong>" . $newval['ingredients'] ."</strong> <br>"; }
?>
<?php }} ?>
Probably the best way would be to check if the variable is an array and then check if it's empty.
As you have made clear if the variable is array and it's not empty, then you should waste processor time to iterate over an array.
So the code would look like this:
if(!empty($var) && is_array($var)) {
foreach($var as $key => $value) {
echo $key . ' => ' . $value;
}
}

Categories