Reputation: 37
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.
Upvotes: 1
Views: 87
Reputation: 41
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 );
Upvotes: 0
Reputation: 10111
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"
)
);
Upvotes: 0
Reputation: 164731
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(...);
Upvotes: 2