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'/>";
}
Related
I have a case where I am using the code below to populate a template of sorts. Within the templates' javascript I would individually check the data attribute field I setup, essentially causing me to have multiple JS files instead of one that is shared. I then thought I could use a generic name field too, but prepend a number through the loop.
For example, with the line of code below where the `name="testField". I want to see if there is a way that I can add a number, but auto increment it through the loop with php.
Is this possible?
echo '<div class="markerItem" name="testField' . $number . '" "data-marker="' . $marker_data . '">';
PHP Code
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $key=>$marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" name="testField_'.$key.'" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
Using this, $key is assigned from the array index which will be a number starting from 0 and ending at count($marker_rows)-1.
Suprisingly, I couldn't find an appropriate duplicate for this.
You can easily increment or decrement variables in PHP.
$number = 0;
foreach ($marker_rows as $marker_row) {
...
$number++; // $number will now be $number+1
}
You can use $number++ directly in your attribute (if concatenating) as this will return the current $number then increment the value.
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]);
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.
I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.
What i want to do is read rssfeed, so I already did it, but I display as foreach loop, so how can I only display 5 records ? now I get more than 10 records, but I only need top 5 records, Isn't anyway php, javascript or jquery make it only show 5 records?
here is my code to read the rss file:
function getrssFeed($feed_url) {
$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
echo "<ul>";
foreach($x->channel->item as $entry) {
echo "<li><a href = '$entry->link' title='$entry->title'><h3>" . $entry->title . "</h3></a>" . $entry->pubDate . "<br /><br />" . strip_tags($entry->description) . "</li>";
}
echo "</ul>"; }
getrssFeed("http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss");
thank you
the easiest way would be to stop your loop after 5 iterations:
$i = 0;
foreach($x->channel->item as $entry) {
// do something
$i++;
if($i==5){
break;
}
}
another (more beautiful) way would be to use a for-loop instead of foreach:
for($i=0; $i<=min(5, count($x->channel->item)); $i++) {
$entry = $x->channel->item[$i];
// do something
}
EDIT :
thanks to Juhana, i changed the code to take that into account.
Try putting a counter in your foreach loop with an if statement to check when the counter is over 5. If the counter is under 5 -> display RSS post, counter++. Else -> Exit loop.
Why not use a simple for loop instead?
for($i = 0, $i <= 5, $i++) {
echo "<li><a href = '$x->channel->item[$i]->link' title='$x->channel->item[$i]->title'><h3>" . $x->channel->item[$i]->title . " </h3></a>" . $x->channel->item[$i]->pubDate . "<br /><br />" . strip_tags$x->channel->item[$i]->description) . "</li>";
}
You can use jQuery feed Plugin.
$('div.feed').Feed({
count:5;
});
<div class="feed" link="http://thestar.com.my.feedsportal.com/c/33048/f/534555/index.rss" ></div>
Feeds would be loaded to container feed.