I have the following PHP code:
function button1($attr, $text) {
$data = "<button ";
foreach($attr as $names => $specs) {
$data .= $names . "='" . $specs . "' ";
}
$data .= ">" . $text . "</button>\n";
echo $data;
}
function span1($attr, $text) {
$data = "<span ";
foreach($attr as $names => $specs) {
$data .= $names . "='" . $specs . "' ";
}
$data .= ">" . $text . "</span>\n";
echo $data;
}
button1(
array( "type" => "button",
"class" => "navbar-toggle",
"data-toggle" => "collapse",
"data-target" => ".navbar-collapse"
),
span1(
array( "class" => "sr-only" ),
"Toggle navigation"
)
);
From the code above, I want the result to appear like this:
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse' >
<span class='sr-only' >Toggle navigation</span>
</button>
But instead it appears like this:
<span class='sr-only' >Toggle navigation</span>
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse' ></button>
What must I do to get the result I want? Thanks for your help.
Simple, NEVER echo from functions. The problem is, span1() is being evaluate first which results in its echo executing. It also returns nothing to be used as the button1() $text argument. Then the button1() echo is executed, printing its contents to the output stream after the span1() echo.
Change the last line of each function to
return $data;
and execute it via
echo button1(...);
Replace your PHP code with this,
You have to return $data into functions and also echo button1();
<?php
function button1($attr, $text) {
$data = "<button ";
foreach($attr as $names => $specs) {
$data .= $names . "='" . $specs . "' ";
}
$data .= ">" . $text . "</button>\n";
return $data;
}
function span1($attr, $text) {
$data = "<span ";
foreach($attr as $names => $specs) {
$data .= $names . "='" . $specs . "' ";
}
$data .= ">" . $text . "</span>\n";
return $data;
}
echo button1(
array( "type" => "button",
"class" => "navbar-toggle",
"data-toggle" => "collapse",
"data-target" => ".navbar-collapse" ),
span1(
array( "class" => "sr-only" ),
"Toggle navigation"
)
);
Hello use below code for your desired output
function button1($attr, $text)
{
$data = "
foreach($attr as $names => $specs)
{
$data .= $names . "='" . $specs . "' ";
}
$data .= ">" . $text . "</button>\n";
return $data;
}
function span1($attr, $text)
{
$data = "<span ";
foreach($attr as $names => $specs)
{
$data .= $names . "='" . $specs . "' ";
}
$data .= ">" . $text . "</span>\n";
return $data;
}
$str = span1(
array( "class" => "sr-only" ),
"Toggle navigation"
);
echo button1(
array( "type" => "button",
"class" => "navbar-toggle",
"data-toggle" => "collapse",
"data-target" => ".navbar-collapse"
),
$str
);
Related
I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>
The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}
Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);
I am trying to add wheres to my query depending on what's coming in from GET:
public function index($type_id) {
$Product = new Product;
$Product->where('type_id', $type_id);
if(array_key_exists('ages', Input::get())) {
$Product->where('age_id', $_GET['ages']);
}
$products = $Product->get();
$productsPaginated = $Product->where('type_id', $type_id)->paginate(2);
return View::make('products.products', array(
'products' => $products,
'productsList' => $productsPaginated
)
);
}
But all it's doing is bringing back every record.
What am I doing wrong?
This is how I'm rendering my filters:
$brands = $prices = $ages = $brandsUsed = $agesUsed = array();
$out = '';
foreach ($productsList as $product) {
$brands[$product->brands->id] = $product->brands->brand;
$brandsUsed[] = $product->brands->id;
$prices[] = $product->price;
$ages[$product->ages->id] = $product->ages->age;
$agesUsed[] = $product->ages->id;
}
$brandsUsed = array_count_values($brandsUsed);
$brands = array_unique($brands);
$params = Input::get();
$lastParams = http_build_query($params);
unset($params['brand']);
$params = http_build_query($params);
if (count($brands) > 0) {
$out .= '<h5>Brands</h5>';
foreach ($brands as $brandId => $brandName) {
if (stristr($lastParams, '&brand=' . $brandId) || stristr($lastParams, 'brand=' . $brandId)) {
$out .= '<a class="filter-link" href="' . Request::path() . '?' . $params . '">';
} else {
$out .= '<a class="filter-link" href="' . Request::path() . '?' . $params . '&brand=' . $brandId . '">';
}
$out .= '<span class="cbox">';
if (stristr($lastParams, '&brand=' . $brandId) || stristr($lastParams, 'brand=' . $brandId)) {
$out .= '<span class="cbox-checked"></span>';
}
$out .= '</span>';
$out .= $brandName;
$out .= ' (' . $brandsUsed[$brandId] . ')';
$out .= '</a>';
}
}
You cannot create queries on object, you should do it this way:
public function index($type_id) {
$product = Product::where('type_id', $type_id);
if(array_key_exists('ages', Input::get())) {
$product->where('age_id', $_GET['ages']);
}
$productsAll = $product->get();
$productsPaginated = $product->where('type_id', $type_id)->paginate(2);
return View::make('products.products', array(
'products' => $productsAll,
'productsList' => $productsPaginated
)
);
}
You should also consider if it makes any sense to get all products and also paginated products. If you have many products in your database it will take long time to get all your products.
I'm also not sure what exactly you want to get for $productsPaginated. I think you will need here building new query:
$productsPaginated = Product::where('type_id', $type_id)->paginate(2);
EDIT
As you want to get count of products with only one filter, you should use here:
public function index($type_id) {
$product = Product::where('type_id', $type_id);
$productCount = $product->count();
if(array_key_exists('ages', Input::get())) {
$product->where('age_id', $_GET['ages']);
}
$productsPaginated = $product->paginate(2);
return View::make('products.products', array(
'productsCount' => $productCount,
'productsList' => $productsPaginated
)
);
}
$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]
So I just want to go through the $rows array, display $rows[0] as one contact and $rows[1] as another. For some reason, the information in is not looped, it only shows the second entry (or if there are more than two, whatever the last entry is). The thing I am not understanding is why when I echo the information without a div, it loops through and displays information for both entries. I've tried using both foreach loops and for ($i=0; $i
$rows[0] = array(
'picture' => 'userImage',//$jpeg[$i],
'givenname' => '',//$info[$i]["givenname"][0],
'sn' => '',//$info[$i]["sn"][0],
'mail' => '#.com',//$info[$i]["mail"][0],
);
$rows[1] = array(
'picture' => 'userImage',//$jpeg[$i],
'givenname' => '',//$info[$i]["givenname"][0],
'sn' => '',//$info[$i]["sn"][0],
'mail' => '#.com',//$info[$i]["mail"][0],
);
//User contact card
for ($i=0; $i<count($rows); $i++){
$strCard[$i] = '';
$strCard[$i] .= " <div class='search-card'>" . $rows[$i]['picture'] . "
<p><b>" . $rows[$i]['givenname'] . " " . $rows[$i]['sn']. "</b></p>
<p><a href='mailto:" . $rows[$i]['mail'] . "'>" . $rows[$i]['mail']. "</a></p>
<div class='member-roles'>";
$strCard[$i] .= "<table>";
$strCard[$i] .= "<tr><th>Role</th><th>Centre</th></tr>";
echo $i.'===='.$rows[$i]['picture'].'<br />';
echo $i.'===='.$rows[$i]['givenname'].'<br />';
echo $i.'===='.$rows[$i]['sn'].'<br />';
echo $i.'===='.$rows[$i]['mail'].'<br />';
}
foreach ($strCard as $key => $value) {
return $strCard[$key];
}
}
}
this is because you are probably executing this code inside of a function and using return instead of echo....taken from the php manual:
"If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call...."
http://us3.php.net/return
I think you should use the value of the foreach loop like this
foreach ($strCard as $value) {
return $value
}
Im not sure how is this useful for you, if you want to return the whole string you can try something like this
$string = '';
foreach ($strCard as $value) {
$string.=$value;
}
Not 100% sure, but it seems like maybe you're wanting this
for ($i=0; $i<count($rows); $i++){
$strCard[$i] = '';
$strCard[$i] .= " <div class='search-card'>" . $rows[$i]['picture'] . "
<p><b>" . $rows[$i]['givenname'] . " " . $rows[$i]['sn']. "</b></p>
<p><a href='mailto:" . $rows[$i]['mail'] . "'>" . $rows[$i]['mail']. "</a></p>
<div class='member-roles'>";
$strCard[$i] .= "<table>";
$strCard[$i] .= "<tr><th>Role</th><th>Centre</th></tr>";
}
foreach ($strCard as $cardEntry) {
echo $cardEntry;
}
Or to simplify it
for ($i=0; $i<count($rows); $i++){
$strCard = '';
$strCard .= " <div class='search-card'>" . $rows[$i]['picture'] . "
<p><b>" . $rows[$i]['givenname'] . " " . $rows[$i]['sn']. "</b></p>
<p><a href='mailto:" . $rows[$i]['mail'] . "'>" . $rows[$i]['mail']. "</a></p>
<div class='member-roles'>";
$strCard .= "<table>";
$strCard .= "<tr><th>Role</th><th>Centre</th></tr>";
echo $strCard;
}
$strCard[$i] = ''; needs to be outside the loop to start the variable, otherwise everytime the loop starts, it writes over the contents.
I am trying to get two foreach loop by explode with two delimiters <> and "\n" but getting error. Warning: Invalid argument supplied for foreach()
Here is my code
<?php
$specifications = $scooter_meta->get_the_value('specifications');
$titles = explode('<>', $specifications);
$descs = explode("\n", $specifications);
echo '<dl>';
foreach($titles as $title => $descs){
echo '<dt>' . $title . '</dt>';
foreach($descs as $desc){
echo '<dd>' . $desc . '</dd>';
}
}
echo '</dl>';
?>
The value entering into textarea something like this Title here<>this is the first scooter ever made.
Title here 2<>another line for specification In fact I would like to make it like <title 1> here detail text
Thanks a lot
actually you should do something like this
<?php
$specifications = $scooter_meta->get_the_value('specifications');
$descs = explode("\n", $specifications);
echo '<dl>';
foreach($descs as $desc){
$title = explode('<>', $desc);
echo '<dt>' . $title[0] . '</dt>';
for($i=1; $i<=count($title); $i++){
echo '<dd>' . $title[$i] . '</dd>';
}
}
echo '</dl>';
?>
The $descs variable isn't an array because the first foreach loop sets $descs.
See this line :
foreach($titles as $title => $descs){
$specifications = $scooter_meta->get_the_value('specifications');
$titles = explode('<>', $specifications);
echo '<dl>';
foreach($titles as $title => $descs){
echo '<dt>' . $title . '</dt>';
$descs = explode("\n", $descs);
foreach($descs as $desc){
echo '<dd>' . $desc . '</dd>';
}
}
echo '</dl>';