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;
}
}
Related
This question already has answers here:
How does true/false work in PHP?
(6 answers)
Closed 2 years ago.
I'm trying to find and output the value from a specific key.
$name = 'G';
$ids = array();
foreach($arrayChart as $key){
$foundAtPosition = strpos($key['Name'], $name);
if ($foundAtPosition === false ||
$foundAtPosition > 0) {
continue;
}
$ids[] = $key['ID'];
}
echo join(',', $ids) . "\n";
Here is the array
$arrayChart = array(
array(
"Name" => "Mike G",
"ID" => "0001234",
"Hours" => 38
),
array(
"Name" => "Mike L",
"ID" => "0005678",
"Hours" => 42
)
array(
"Name" => "John G",
"ID" => "0003615",
"Hours" => 42
)
);
This code above was provided by #zedfoxus
He helped me with a previous problem.
I want to find the ID number from the key value ID by using the last name letter "G" from key Name.
I want to output them in the same line. The problem with the above function is that it doesn't print anything.
Please see the answer below.
<?php
$arrayChart = array(
array(
"Name" => "Mike G",
"ID" => "0001234",
"Hours" => 38
),
array(
"Name" => "Mike L",
"ID" => "0005678",
"Hours" => 42
),
array(
"Name" => "John G",
"ID" => "0003615",
"Hours" => 42
)
);
$name = 'G';
$ids = array();
foreach($arrayChart as $key){
$foundAtPosition = strpos($key['Name'], $name);
if ($foundAtPosition) {
$ids[] = $key['ID'];
}
}
echo join(',', $ids) . "\n";
?>
I have an array consisting of seat number in the following format
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
?>
And also the retrieved data of reserved seats by users which comes in this format
<?php
$seat = array();
$sql = $db->query("SELECT booked_seat FROM mybooking where bus_id = '{$l}'");
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r){
$seat[] = $r['booked_seat'];
}
print_r($seat)
// Array ( [0] => A1 [1] => D2 )
?>
All I am trying to achieve is to disable the selected seats in a HTML select like I tried doing here
<?php
$keys = array_keys($seatnumbers);
$values = array_values($seatnumbers);
$skeys = array_keys($seat);
$val = array_values($seat);
for($i = 0; $i < 14; $i++ )
{
if($keys[$i] == $val[$i]){
echo "<option disabled>". $keys[$i]. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $keys[$i]."-". $val[$i]. "(Available)</option>";
}
}
?>
But only the first option showed booked. How do compare for two arrays to disabled the reserved seats.
Here is the result of what I tried
Using prepared statements and also using PDO::FETCH_COLUMN to save having to process the result set from the SQL further. The code has comments to show how this is done.
You will have to change the output, but it matches what you have enough to modify it...
$query = "SELECT booked_seat FROM mybooking where bus_id = :busID";
$sql = $db->prepare($query);
$sql->execute(["busID" => $l]);
// Fetch an array with just the values of booked_seat
$seat=$sql->fetchAll(PDO::FETCH_COLUMN, 0);
// Flip array so the seat name becomes the key
$seat = array_flip($seat);
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
foreach ( $seatnumbers as $seatName => $number ) {
echo $seatName;
// If the key is set in the seat array, then it is booked
if ( isset($seat[$seatName]) ){
echo " Seat booked".PHP_EOL;
}
else {
echo " Seat not booked".PHP_EOL;
}
}
This is a typical task for using foreach
<html>
<head></head>
<body>
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
$seat = array(
"0" => "A1","1" => "D2",
"2" => "E1","3" => "E2","4" => "E3"
);
echo "<select>";
foreach ($seatnumbers as $ikey=>$ivalue)
{
if(in_array($ikey,$seat)){
echo "<option disabled>". $ikey. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $ikey."-". $val[$i]. "(Available)</option>";
}
}
echo "</select>";
?>
</body>
</html>
I want to fill an array in a while loop.
I want to display this array like this :
category 1 => Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
category 2 = Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
ect ........
Here's my current code in my while loop
$array_cat[] = array(
array(
'category' => $cat,
array(
'company' => array(
'name' => $name,
'city' => $city,
'CEO' => $ceo
)
)
)
);
My code WHen I display it
foreach ($array_cat as $item) {
foreach ($array_cat['category'] as $company_display) {
echo $company_display['company']['name'][];
}
}
Thanks for the help ;)
try this:
$array1 = array('category1' =>
array('Company A' =>
array('name', 'city', 'CEO')),
'category2' =>
array('Company B' =>
array('name', 'city', 'CEO')));
foreach ($array1 as $key => $value)
{
foreach ($value as $key1 => $value1)
{
echo "<pre>";
print_r($value1);
echo "</pre>";
}
}
Problem is in your inner foreach loop
There is a problem in inner foreach loop and echo line.
Replace $array_cat by $item and in echo line there is an error:
Cannot use [ ] for reading
By following way, you can achieve your goal.
foreach ($array_cat as $item) {
foreach ($item as $company_display) {
echo $company_display['category']['company']['name'];
}
}
How to create this multidimensional array in PHP
If I would design an array for that, i would do something like this:
$array = array(
//Category 1, nameless i assume?
array(
//Companies
"Company A" => array(
//Company properties
"name" => "My A company",
"city" => "Some city that starts with an A",
"CEO" => "Some CEO that starts with an A"
),
"Company B" => array(
//Company properties
"name" => "My B company",
"city" => "Some city that starts with an B",
"CEO" => "Some CEO that starts with an B"
),
),
//Category two, nameless i assume
array(
//Companies
"Company C" => array(
//Company properties
"name" => "My C company",
"city" => "Some city that starts with an C",
"CEO" => "Some CEO that starts with an C"
),
"Company D" => array(
//Company properties
"name" => "My D company",
"city" => "Some city that starts with an D",
"CEO" => "Some CEO that starts with an D"
),
),
);
Then, if i wanted to get some data out of it, i could do something like this:
$companyAcity = $array[0]['Company A']['city'];
echo $companyAcity;
If I wanted to loop in the array, i could so something like this:
for($categoryID = 0; categoryID < count($array); $i++) {
//Prints data for each category it loops through.
echo $array[$categoryID];
//Loops through the companies contained in the current category where it's looping through
foreach($array[$categoryID] as $companyName => $companyData) {
echo $companyName;
echo $companyData['name'];
}
}
I want to fill an array in a while loop.
If you want to add data to the array while looping in it, you can do something like this:
for($categoryID = 0; categoryID < count($array); $i++) {
$array[$categoryID][] = $categoryID +1;
}
<?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.
I have a multidimensional array which I want to display in a foreach loop. I've been looking at lots of tutorials but I haven't been able to make it work yet.
This is my array and foreach loop:
$events = array(
array( Name => "First Event",
Date => "12/13/14",
Time => "12:13"
Description => "event description"
),
array( Name => "Second Event",
Date => "12/13/14",
Time => "12:13",
Description => "event description"
),
array( Name => "Third Event",
Date => "12/13/14",
Time => "12:13"
Description => "event description"
)
);
foreach($events as $event) {
echo "<div class=\"event\"><strong>";
echo $event[Name];
echo "</strong><em>";
echo $event[Date] . " at " . $event[Time];
echo "</em><div>";
echo $event[Description];
echo "</div></div>";
}
and here is how I want it to display:
<div class="event">
<strong>Event Name</strong><em>Date at Time</em>
<div>
Description
</div>
</div>
I would appreciate any help you could give. Thanks!
The keys are missing quotes and Time => "12:13" missing comma "," at the end:
<?php
$events = array(
array( "Name" => "First Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
),
array( "Name" => "Second Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
),
array( "Name" => "Third Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
)
);
foreach($events as $event) {
?>
<div class="event">
<strong><?php echo $event["Name"];?></strong><em><?php echo $event["Date"];?></em>
<div><?php echo $event["Description"];?></div>
</div>
<?php
}
?>
Output
First Event 12/13/14
event description
Second Event 12/13/14
event description
Third Event 12/13/14
event description
The keys should be in quotes. E.g.: 'Name' rather than Name
<?php foreach($events as $event): ?>
<div class="event">
<strong><?php echo $event['Name'] ?></strong><em><?php echo $event['Date'] ?> at <?php echo $event['Time'] ?></em>
<div>
<?php echo $event['Description'] ?>
</div>
</div>
<?php endforeach; ?>
Try this:
foreach($events as $record) {
$name = $record["name"];
$date = $record["date"];
$time = $record["time"];
$description = $record["description"];
print("
// your html code with the variables here
");
}