I need to wrap both my arrays in their own wrapping div outside of the foreach loop.
function foo() {
//my foreach loops
$top_content[] = $top;
$bottom_content[] = $bottom;
return array($top_content, $bottom_content);
}
Ideally I would be able to:
function foo() {
//my foreach loops
$top_content[] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom . '</div>';
return array($top_content, $bottom_content);
}
but then I get an error of: Notice: Array to string conversion
any help appreciated.
function foo() {
//my foreach loops
$top_content[0] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[0] = '<div class="wrapper-two">' . $bottom . '</div>';
return array($top_content, $bottom_content);
}
This is so because you are trying to concatenate array with string. Since $top and $bottom could have been initialized as array before.
$top_content[0] = '<div class="wrapper-one">' . $top . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom . '</div>';
So my guess is you must be doing creating $top and $bottom as array and trying to concatenate at the end of for-each loop.
You can still do it like this.
$topContents = implode('', $top);
$bottomContents = implode('', $bottom);
$top_content[0] = '<div class="wrapper-one">' . $topContents . '</div>';
$bottom_content[] = '<div class="wrapper-two">' . $bottom . '</div>';
The trick is to use php's implode function to concatenate array first. After concatenation it returns string. This string can then further be concatenated with other strings.
Give it a try and let us know.
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 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]);
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $menu[$key] . '">' . $menu[$key] . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu[1]); ?>
What i basically want to do is to pass a specific array value when i'm echoing out the menu.
I'm building a single page website with anchors and i want to pass value's so i can echo out the "top"-link.
I'm stuck at the point on how to pass the $key value trough the function.
**edit: I'm trying to print specific links. I want a function that is able to print out an link but i want to specify the link to print via the function argument.
for example:
<?php echo main_menu($key = '0'); ?>
result:
prints url: top
<?php echo main_menu($key = '2'); ?>
result:
prints url: photography
**
(A lack of jargon makes it a bit harder to explain and even harder to google.
I got my books in front of me but this is taking a lot more time than it should.)
You either need to pass the entire array and loop, or pass a single array item and not loop:
Single Item:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
$return .= '<a class="menu" href="index.php#' . $menu . '">' . $menu . '</a>' . PHP_EOL .'';
$return .= '</div>';
return $return;
}
echo main_menu($menu[1]);
Entire Array:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach($menu as $value) {
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
echo main_menu($menu);
You don't need $menu[$key] just use the $value.
Should you not just be using $value inside your loop? And passing the entire array rather than one item of the $menu array?
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu); ?>
Try:
echo main_menu($menu); // You will get your links printed
Instead of
echo main_menu($menu[1]); // In this case error is occured like : **Invalid argument supplied for foreach**
NOTE: You can use $value instead of $menu[$key]
I would like to create nested divs dynamically, preferably without JavaScript.
So if you have n number of DIVs, DIV1 contains DIV1 which contains DIV3 etc…
How would I code that in PHP?
function recursiveDiv($num) {
$html = '<div id="div'.$num.'">%s</div>';
for($i = $num - 1; $i >= 1; $i--) {
$html = '<div id="div'.$i.'">'.$html.'</div>';
}
return $html;
}
echo sprintf(recursiveDiv(5), 'Hello World');
Untested but should give you want you want.
Here is a simple loop example using $n = 3. You can change $n to any number and it will nest div tags for you. I'm not entirely sure why you would want to do this, but here it is.
$openingTags = '';
$closingTags = '';
$n = 3;
for ($i = 0; $i < $n; ++$i) {
$openingTags .= '<div id="div' . $i . '">';
$closingTags .= '</div>';
}
echo $openingTags . 'Hello World' . $closingTags;
This code should allow you to create the nested divs and also populate them with content. Replaced orginal code with below, this should work but its untested
$result = mysql_query("SELECT * FROM table");
$count = mysql_num_rows($result);
$html = '';
$end_html = '';
while($row = mysql_fetch_object($result)){
$html .= '<div id="div'.$count.'">'.$row->textfield; # any database column
$end_html .= '</div>';
$count--;
}
echo $html . $end_html;
While others are suggesting using mathematical solutions based on for loops, you can do this a bit more explicitly—clearly setting classnames—by using an array like this:
// Set the DIVs array.
$divs_array = array();
$divs_array[] = 'DIV1';
$divs_array[] = 'DIV2';
$divs_array[] = 'DIV3';
Now with that array set, you can use implode to take the content of those arrays and set them as DIV class values like this. Note the implode logic might seem confusing, but look at what it creates and look at how the code is set and it makes more sense after a while:
// Set the DIVs.
$div_opening = $div_closing = '';
if (!empty($divs_array)) {
$div_opening = '<div class="' . implode($divs_array, '">' . "\n" . '<div class="') . '">';
$div_closing = '</div><!-- .' . implode(array_reverse($divs_array), '-->' . "\n" . '</div><!-- .') . ' -->';
}
And then you can set the content between the $div_opening and $div_closing values like this:
// Return the content wrapped in the DIVs.
echo $div_opening
. '<p>Hello world.</p>'
. $div_closing
;
The output would be something like this:
<div class="DIV1">
<div class="DIV2">
<div class="DIV3">
<p>Hello world.</p>
</div><!-- .DIV3 -->
</div><!-- .DIV2 -->
</div><!-- .DIV1 -->
Note my personal coding style is to—whenever possible—set comments after each DIV that clearly shows what that </div> is actually closing. So that is what the comments like <!-- .DIV3 --> refer to; feel free to adjust to fit your own coding needs and style.