How to add html inside an if else statement in php? - php

I have this code where if something then display a link, else display another link. the if and else are php code, and the links are html as you will know, but I was wondering how do you make it so it will not give me any errors, how do I combine php with html?
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
Leave Society;
} else {
Join Society;
}

This might help you. This one is from the basics of PHP:
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
echo "<a href='file.php' class='socbuttons'>Leave Society</a>";
} else {
echo "<a href='anotherfile.php' class='socbuttons'>Join Society</a>";
}
}
?>

Remember PHP should be surrounded by <?php ?>. Simply end the "PHP part" and then start it again when you finished your HTML.
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
?> Leave Society <?
} else {
?> Join Society<?
}
Also, you can write HTML in echo statement, but you should escape some special characters like " to not interfere with the php code itself.
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) {
echo "Leave Society";
} else {
echo "Join Society";
}
See http://php.net/manual/en/function.echo.php to more information.

Try this
<?php foreach ($user_socs as $user_soc) {
if ($soca == $user_soc) { ?>
Leave Society;
<?php } else { ?>
Join Society;
<?php }

Use alternate syntax:
<?php
$aUserSocs = array( 'link1', 'link2', 'link3' );
$soca = 'link2';
$iCountUserSocs = count( $aUserSocs );
for( $i = 0; $i < $iCountUserSocs; ++$i ):
?>
<?php if( $soca == $aUserSocs[ $i ] ): ?>
Leave Society;
<?php else: ?>
Join Society;
<?php endif; ?>
<?php endfor; ?>

Related

How to set "class = active" for second tab?

I have some tabs. In that sometimes first tab is "introduction" and sometimes "outline" is first tab. I have set introduction class=active when it comes first. But when outline comes first I am not getting how to set its class as active.
code is like below
<ul class="nav-tabs" role="tablist">
<?php
$tabs = array();
if(!$sessId == "" && !$checkcourse){
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>true, "comment"=>true);
} else if($sessId == "") {
$tabs = array("introduction"=>true, "outline"=>true,"announcement"=>false,"discussion"=>false,"review"=>true, "student"=>false, "comment"=>true);
} else {
$tabs = array("introduction"=>false, "outline"=>true,"announcement"=>true,"discussion"=>true,"review"=>true, "student"=>true, "comment"=>false);
}
?>
<?php if($tabs['introduction']) { ?>
<li class="active">Introduction</li>
<?php } ?>
<?php if($tabs['outline']) { ?>
<li>Outline</li>
<?php } ?>
<?php if($tabs['review']) { ?>
<li>Review</li>
<?php } ?>
<?php if($tabs['student']) { ?>
<li>Student</li>
<?php } ?>
<?php if($tabs['comment']) { ?>
<li>Comment</li>
<?php } ?>
<?php if($tabs['announcement']) { ?>
<li>Announcement</li>
<?php } ?>
<?php if($tabs['discussion']) { ?>
<li>Discussion</li>
<?php } ?>
</ul>
Simple check with ternary operator is:
<?php if($tabs['outline']) {?>
<li <?=$tabs['introduction']? '' : ' class="active"';?>>Outline</li>
<?php } ?>
So you check if $tabs['introduction'] isset then you don't need class="active", else - add this class.
Update:
But as first item of tab can change, I advise to create simple foreach:
$is_first = true;
foreach ($tabs as $tab_name => $value) {
if ($value) {
echo '<li' . ($is_first? ' class="active"' : '') . '>' . $tab_name . '</li>';
$is_first = false; // fix that we have first value here
}
}
Here your main problem is how to link href value and caption.

Switching from "if" to "elseif" breaks code

I'm using multiple if statements to check a containing div, and output an image based on the container name. The code was working fine until I add a final "else" or change the if's out to elseif and I can't figure out why that's happening. When I try to add the else or elseif, the entire page fails to load. Any idea why this is happening?
<?php
if($viewMore['container_type'] == 'Large IMG' || $viewMore['container_type'] == 'Gallery') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'large_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$large = 0; foreach ($photoArray as $photo => $upload): if (++$large == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach ?>
<?php } ?>
<?php
elseif($viewMore['container_type'] == 'Medium IMG') {
$photoSql = "SELECT * FROM `cms_uploads` WHERE (`tableName`='site_content' AND `recordNum` = '".$viewMore['num']."' AND `fieldname`= 'small_images') ORDER BY `order`";
$photoResult = $database->query($photoSql);
$photoResultNum = $database->num_rows($photoResult);
$photoArray = array();
while($photoResultRow = $database->fetch_array($photoResult)) {
array_push($photoArray, $photoResultRow);
}
$medium = 0; foreach ($photoArray as $photo => $upload): if (++$medium == 2) break;
?>
<img class="features" src="<?php echo $upload['urlPath'] ?>">
<?php endforeach; ?>
<?php } ?>
<?php else { ?> SOMETHING HERE <?php } ?>
EDIT:
Other notes
I've tried wrapping the break; in brackets because I thought that piece following the count might be messing with something. Also removing the counter altogether or adding a semi colon after the endforeach didn't help.
Whenever you close your PHP block, think about all the text/HTML outside it being put into PHP's echo function.
What gave me alarm bells was this part:
<?php } ?>
<?php else { ?> ...
What that translates into is:
if (...) {
} echo "[whitespace]"; else {
}
which clearly makes your else block unexpected.
You should not close the PHP block between your closing if and opening else, i.e. do this instead:
...
} else {
...

foreach() executing same line again and again

I have a sql field wehre values are like
1,2,3,4,5,6
if fetch those values and explode them below
$amenities = 1,2,3,4,5,6
$amenities_check = explode( "," , $amenities );
Then I run a foreach loop
<?php
$i = 1;
foreach($amenities_check as $amenities_conf)
{
if( $amenities_conf != "" && $amenities_conf == 6)
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
if ($i++ == 1) break;
}
?>
Now the problem is that this loop is display the same line 6 times and display the correct class of li when it meets the 6 digit in the data if i apply $i++ it only check the first data in the dataset.
Any help that foreach look for the desired values like 1 2 3 and do the function according to it ..
Thanks
Is this what you are looking for?
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else {
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
}
?>
EDIT:
<?php
foreach($amenities_check as $amenities_conf) {
if ($amenities_conf == 6) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
}
?>
<li class="not_amen">Smoking Allowed</li>
or like the guys above said, use in_array().
<?php
if (in_array("6", $amenities_check)) {
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
?>
<li class="not_amen">Smoking Allowed</li>
From the comments, what you actually want to know is if there is a 6 anywhere in the array, so you don't want to be outputting anything at all in the loop. The simplest approach is to use the fairly self-explanatory in_array function; as simple as this:
if( in_array('6', $amenities_conf) )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}
Alternatively, break apart your logic from your display by looping through the database result once and preparing structured data based on it. The below is probably over-kill for this example, but shows a general approach:
// While retrieving data from the DB
$amenity_names = array(
1 => 'pets',
// ...
6 => 'smoking'
);
$included_amenities = array();
$amenities_check = explode( "," , $amenities );
foreach ( $amenities_check as $amenity )
{
$name = $amenity_names[$amenity];
$included_amenities[$name] = true;
}
// In the View / template code
if( $included_amenities[['smoking'] )
{
?>
<li class="available_amen">Smoking Allowed</li>
<?php
}
else
{
?>
<li class="not_amen">Smoking Allowed</li>
<?php
}

How do I close this php statement correctly?

Im attempting to create a simple list out of some elements I stole from a more complex list of rows etc., I just need list out the values in single row separated by commas.
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
;} ?>
;} ?>
<?php } ?>
The Result I get follows "3 ;} ?> 3 ;} ?> 4 ;} ?> 3 ;} ?> "
Thanks in advance
Micah
try this
<?php
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
}
}
?>
Fore more detail PHP Tags
Change the #9, #10, remove #11 line. What you're doing is printing characters: ;} ?>
and are syntactically wrong. This is proper:
<?php foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
echo nbf_common::nb_strlen($document_item->product_code);
}
} // here
} // here
?>
Also for the "comma separated" part, put required values in a variable and echo it at the end.
Could be like this:
<?php
$string = '';
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$string .= nbf_common::nb_strlen($document_item->product_code).',';
}
}
}
echo rtrim($string, ','); // remove the last comma
?>
or use a temp array to glue them at the end:
<?php
$lines = array();
foreach ($document_items as $document_item)
{
if ($document_item->document_id == $document->id)
{
if (nbf_common::nb_strlen($document_item->product_code) > 0)
{
$lines[] = nbf_common::nb_strlen($document_item->product_code);
}
}
}
echo implode(',', $lines); // bind them with comma
?>
I'm not sure why you have all those extra ?>. The pattern is:
<?php
// PHP code goes here
?>
i.e. every <?php has a matching ?>; no more, no less.1
1. Other than the case that #Mihai points out in the comment below...
To understand the php tags you might want to think that you are in an HTML file and you are intrerrupting the HTML flow with
When writing PHP only files (classes, interfaces, traits lists of functions and similar grouping of application code with no templating) it is advisable to open at the very first character in the file and not end it at all.
When writing template files however it is advisable to use php's alternate syntax:
<?php if($x): ?>
<?php elseif($y): ?>
<?php else: ?>
<?php endif; ?>
Instead of the standard:
<?php if($x) { ?>
<?php } else if($y) { ?>
<?php } else { ?>
<?php } ?>

Wordpress PHP: Conditional Statement wihtin a Conditional Statement

How would I place the following:
<?php if (function_exists('premium_slider')){ premium_slider(1); }; ?>
Within the echo of this:
<?php if(is_page(2)){ echo ''; } ?>
Obviously I can't do this:
<?php if(is_page(2)){ echo '<?php if (function_exists('premium_slider')){ premium_slider(1); }; ?>'; } ?>
<?php
if (is_page(2) && function_exists('premium_slider')){ echo premium_slider(1); };
?>
With else:
if (is_page(2) && function_exists('premium_slider')) {
echo premium_slider(1);
} else {
echo "SO Rocks!";
}
Alternatively:
echo is_page(2) && function_exists('premium_slider') ? premium_slider(1) : 'SO Rocks!';
<?php
if (is_page(2) && function_exists('premium_slider')) {
echo premium_slider(1);
}
?>
You can use this code exactly:
<?php
if (is_page(2) && function_exists ( 'premium_slider' )) {
echo premium_slider ( 1 );
} else premium_slider ( 2 );
?>
You are using closing } at wrong place.

Categories