Printing words and PHP variable - php

I am trying to print a list of items, with the calculated of the quantity next to it. So far, only the quantity is printed next to the image. I need the value (i.e Apple) to appear as well. The value did appear, until I added 'quantity'. Any help would be greatly appreciated.
echo "<br/><br/><br/> You are leaving on ". $_POST["departuredate"]."</p>";
echo "You are returning on ". $_POST["returndate"]."</p>";
$return= strtotime($_POST["returndate"]);
$depart = strtotime($_POST["departuredate"]);
$datediff = $return - $depart;
echo "You are going for <b> ";
$quantity=floor($datediff/(60*60*24));
echo $quantity;
echo " days";
$Yoghurt= 'Yoghurt' + $quantity;
$Apple = 'Apple' + $quantity;
$Banana = 'Banana' + $quantity;
....
$FoodList=array_unique($FoodList);
$img_path = 'empty_checkbox.gif';
if(!empty($FoodList))
{
foreach ($FoodList as $key => $value)
{
echo "<li>" . "<img src='$img_path' />" . " ". $value ."</li>";
}
echo "</ul>";
}

Use . to concat variables to a string, not +. + is the mathematical addition operator. PHP typecasts the string to a 1 and adds it to $quantity.
$Yoghurt= 'Yoghurt' . $quantity;
$Apple = 'Apple' . $quantity;
$Banana = 'Banana' . $quantity;
See string operators for more in-depth information.

In PHP you don't use + to join (concatenate strings), you should use . instead.

Related

PHP - Use variable names with numbers through a loop

In my for loop for ($i = 1; $i <= 3; $i++) i have have html code that will be echod 3 times. The html also using PHP objects ($help).
$help has 3 things, $help->url_1, $help->text_1, $help->icon_1. But through the loop, I want it so that when for example $i is at 2, i want to use $help->url_2, etc. How can i sort of increment the variable name in the echo string of in the loop?
<?php
class Help
{
public $url;
public $text;
public $icon;
}
$help1 = new Help();
$help1->url = 'your url';
$help1->text = 'your text';
$help1->icon = 'url to your icon';
$helps[] = $help1;
//Repeat for other helps (help2, help3, etc.)
?>
Once you have an array of objects, you only need to loop into it using a foreach loop :
foreach ($helps as $help) {
echo "<h3>" . $help->url . "</h3>";
echo "<p>" . $help->text . "</p>";
echo "<img src='" . $help->icon . "' alt='your alt'/>";
}

PHP 'While' within a ForEach loop pulling from SQL DataBase

I have a little table being duplicated several times based on the number of entries there are in my SQL Database, which let's say is about colours. These tables will go one place to the right with each new entry. Within that, I now want, within each entry, to be able to automate an output for a few fields. For example, a single table entry might be 'reds' and now I want to display the different shades of red, i.e. 'shade1', 'shade2', 'shade3', 'shade4' from that, and then the next entry might be 'yellows' and I would want it to display as many yellows there were added, i.e. 'shade1', 'shade2'. My code is like this:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$stmt = $conn->prepare("SELECT * FROM colours");
$stmt->execute();
$colours = $stmt->fetchALL();
if($colours){
$i = 1;
foreach ($colours as $key => $colour) {
$coloursrow1 .='<table >
<tr><th>' . "<b>{$colour['colour']}</b>" . '</th></tr>
<tr><td>' . "<img src='{$colour['shade1']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade2']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade3']}' />" . '</td></tr>
<tr><td>' . "<img src='{$colour['shade4']}' />" . '</td></tr>
</table>';
$i++;
}
}
?>
And I wondered if instead of all the lines like <tr><td>' . "<img src='../colours/reds/shade1.jpg' />" . '</td></tr>, I could put something like
if($colours){
$i = 1; $x = 1;
foreach ($colours as $key => $colour) {
$coloursrow1 .='<table >
<tr><th>' . "<b>{$colour['colour']}</b>" . '</th></tr>';
}
while ($x < 6) {
'<tr><td>' . "<img src='{$colour['shade$x']}' />" . '</td></tr>';
$x++;
}
foreach ($colours as $key => $colour) {
'</table>';
$i++;
}
}
So that it would grab and output them automatically and also giving me the ability to put a cap on how many can be output.
I tried different ways to accomplish this, but I just keep hitting dead ends. I must be doing something wrong(?)
Seems like it would be something like this, since PDO::fetchAll() returns an empty array or false on error. So just iterate over that set directly. Also, the array access is wrong, it should be {$colour['shade'.$x]}.
<?php
error_reporting(E_ALL ^ E_NOTICE);
$stmt = $conn->prepare("SELECT * FROM colours");
$stmt->execute();
$colours = $stmt->fetchALL();
foreach ($colours as $colour) {
$coloursrow1 .= "<table><tr><th><b>{$colour['colour']}</b></th></tr>";
$x = 1;
while ($x < 6) {
$coloursrow1 .= "<tr><td><img src='{$colour['shade'.$x]}' /></td></tr>";
$x++;
}
$coloursrow1 .= '</table>';
}

How to add results of a foreach loop to a variable in PHP

foreach ($_SESSION["products"] as $cart_itm) {
$items = $cart_itm["code"]
. " - " . $cart_itm["qty"]
. " - " . $cart_itm["price"]
. "<br>" ;
echo $items;
}
I have this code which gets every item from my basket and displays them, the problem is when I try to use this variable elsewhere in my code, it only displays the last item in the array, I realised that this is becasue the for loop keeps overwriting the last value . Is there a way I could put all results into one variable or use the loop to assign them too different variables maybe?
I also tried to put
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"]
. " - " . $cart_itm["qty"]
. " - " . $cart_itm["price"]
. "<br>" ;
echo $items;
}
after looking through the forum but that returns me with items is not defined
so I tried to put
$items= ("")
but still get the final result
Any help is appreciated, thanks
You can concatenate you variables together, but you have to initialize your variable first.
(Otherwise you can think of something like: 'I want to concatenate this string to nothing', so this is obvious not going to work, that's why you initialize your variable so, you can say: 'I want to concatenate this string to a empty string')
Something like this:
$items = "";
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
Or you can put them in a array with this:
$items = array();
foreach ($_SESSION["products"] as $cart_itm) {
$items[] = $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
print_r($items);
$items = "";
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
echo $items;
$foo = '';
foreach ($loopable as $item) {
$foo = $foo.'-'.$item;
}
echo $foo;
Make sure to init that variable before the for loop

Getting a random object from an array in PHP

First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);

Getting XML with PHP: how to get attributes from 2 nodes with same name

I am getting attributes from XML nodes and saving them to variables with a for loop as such:
for ($i = 0; $i < 10; $i++){
$group = $xml->Competition->Round[0]->Event[$i][Group];
if($group == "MTCH"){
$eventid = $xml->Competition->Round[0]->Event[$i][EventID];
$eventname = $xml->Competition->Round[0]->Event[$i][EventName];
$teamaname = $xml->Competition->Round[0]->Event[$i]->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->EventSelections[1][EventSelectionName];
echo "<br/>" . $eventid . ": " . $eventname . ", " . $teamaname . "VS" . $teambname;
}//IF
}//FOR
I can save each Event[EventID] and each Event[EventName] but I cannot get the EventSelections[EventSelectionNames] to save.
I am guessing this is because there are multiple (2) <EventSelection>s for each <Event>, this is why I tried to get them individually uising [0] and [1].
The part of the XML file in question looks like:
<Event EventID="1008782" EventName="Collingwood v Fremantle" Venue="" EventDate="2014-03-14T18:20:00" Group="MTCH">
<Market Type="Head to Head" EachWayPlaces="0">
<EventSelections BetSelectionID="88029974" EventSelectionName="Collingwood">
<Bet Odds="2.10" Line=""/>
</EventSelections>
<EventSelections BetSelectionID="88029975" EventSelectionName="Fremantle">
<Bet Odds="1.70" Line=""/>
</EventSelections>
</Market>
</Event>
Can anyone point me in the right direction to save the EventSelectionNames to variables?
Rather than looping and checking for $group, use xpath to select data directly:
$xml = simplexml_load_string($x); // assume XML in $x
$group = $xml->xpath("/Event[#Group = 'MTCH']")[0];
echo "ID: $group[EventID], name: $group[EventName]" . PHP_EOL;
If there are always two <EventSelections>, you can:
echo "Team A: " . $group->Market->EventSelections[0]['EventSelectionName']" . PHP_EOL;
echo "Team B: " . $group->Market->EventSelections[1]['EventSelectionName']" . PHP_EOL;
Otherwise, use foreach:
foreach ($group->Market->EventSelections as $es)
$teamnames[] = $es['EventSelectionName'];
echo "There are " . count($teamnames) . "Teams:" . PHP_EOL;
foreach ($teamname as $teamname) echo $teamname . PHP_EOL;
see it in action: https://eval.in/105642
Note:
The [0] at the end of the code-line starting with $group = $xml->xpath...requires PHP >= 5.4. If you are on a lower version, update PHP or use:
$group = $xml->xpath("/Event[#Group = 'MTCH']");
$group = $group[0];
Michi's answer is more correct and better coded but I also found the adding the node 'Market' to my code worked as well:
$teamaname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[1][EventSelectionName];

Categories