Writing a small program to ask some people their dreams for fun. I'm trying to put the data into an associative array. I want it to come out like this (for example three names:
How many people should I ask their dreams?
*number*
What is your name?
*name*
What is your dream?
*dream*
name's dream is: dream
My code is as follows:
<?php
echo "How many people should I ask their dreams?" . PHP_EOL;
$many = readline();
$dreams = [];
if (is_numeric($many)) {
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
$dreams[] = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
$dreams[] = readline() . PHP_EOL;
}
echo "In jouw bucketlist staat: " . PHP_EOL;
foreach ($dreams as $key => $value) {
echo $key . "'s dream is: " . $value;
}
} else {
exit($hoeveel . ' is geen getal, probeer het opnieuw');
}
?>
It keeps returning this:
0's dream is: *name*
1's dream is: *name*
etcetera.
When you read values from the $dreams array with foreach ($dreams as $key => $value), you're expecting names as keys, but that's not how you inserted the values. You can use the name as the array key like this instead:
for ($i = 1; $i <= $many; $i++) {
echo "What is your name?" . PHP_EOL;
// set a name variable here
$name = readline() . PHP_EOL;
echo "What is your dream?" . PHP_EOL;
// then use that variable as the array key here
$dreams[$name] = readline() . PHP_EOL;
}
Related
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'/>";
}
I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.
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
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];
Continuing from my other question, I now know how to extract the fieldnames into variables with the result stored in them.
However, lets say I wish to output like this:
<?php
echo "Here is field1: ".$row['field1'];
echo "Here is field2: ".$row['field2'];
echo "Here is field3: ".$row['field3'];
?>
And I have over 40 fields in my table, so to avoid having to type them all out like the above, how can I automate it?
foreach ($row as $key => $value) {
echo "Here is '" . $key . "': " . $value . "<br>\n";
}
<?php
for($i = 1; $i < 40; $i++) {
echo "Here is field" . $i . ": ".$row['field' . $i];
}
?>
But I wonder, why do you have 40 columns in your table? Seems like you should redesign it.
foreach ($row as $key => $value) {
echo "Here is ".$key.": ".$value;
}
Or I don't get it:)