What is wrong with my if statement? - php

I had the below code which worked fine until I added an if statement to restrict the loop to only run on certain items in the array. I am now only getting a blank page which suggests there is an error somewhere in my code since adding the if statement, but I can't figure out where.
I'd really appreciate any help on solving this, as well as suggestions on how I could have solved myself (I'm still new to PHP and not sure how to effectively debug this type of issue).
Nb. There is an opening <?php tag not shown in the below snippet.
foreach ($portfolioProjects as $portfolio) {
if ($portfolio['featureContent'] == "Yes") {
?>
<div class="row featurette">
<?php
//for each odd number, change the layout so it looks nice :)
if ($loopCount % 2 == 0) {
echo '<div class="col-md-7">';
} else {
echo '<div class="col-md-7 col-md-push-5">';
}
?>
<h2 class="featurette-heading"><?php echo $portfolio[title]; ?> <span class="text-muted"><?php echo $portfolio[languages]; ?></span>
<?php
//Check array for newTag which will be added to show a tag to the user
if ($portfolio[newTag] == "Yes") {
echo '<span class="label label-success test pull-right"> New!</span>';
}
?></h2>
<p class="lead"><?php echo $portfolio[blurb]; ?></p>
</div><!--end of column1-->
<?php
if ($loopCount % 2 == 0) {
echo '<div class="col-md-5">';
} else {
echo '<div class="col-md-5 col-md-pull-7">';
}
?>
<img class="featurette-image img-responsive center-block" data-src="holder.js/200x200/auto" alt="200x200" src="assetts/200x200.gif" data-holder-rendered="true">
</div>
</div>
<?php
//if statement to stop divider being added if last item in array
$loopCount = $loopCount + 1;
if ($loopCount != $itemsCount) {
echo '<hr class="featurette-divider">';
}
}
}
?>

The easiest way to find out what the problem is, to check your webserver's log file, or turn on error_reporting and display_errors in your php.ini file.
Are newTag and blurb constants or keys in the $portfolio array? If they are keys, you should use apostrophes.
if ($portfolio['newTag'] == "Yes") {
and
<p class="lead"><?php echo $portfolio['blurb']; ?></p>

You forgot to wrap array keys in quotes
`$portfolio['title']
$portfolio['languages']
$portfolio['newTag']
$portfolio['blurb']`

Related

How to I fix this if/else tree? PHP

I am trying to program a sub-system for students on my website, I tried using these if/else statements to determine some outputs if the parameters match with the user information they have. So if a user is a student they can contact other people that are students and cant contact other users that are not students, and vice versa. The code I tried is below. The problem is that the code shows the error message and the message buttons at the same time whether or not the user is or is not a student. TIP: This PHP code is in a .phtml file, hence the amount of PHP opening and closing tags.
<?php if($dc['user']['student'] !== 0){ ?>
<?php if(Dc_IsStudent($dc['popover']['user_id']) == true){ ?>
<div class="user-button user-follow-button"><?php echo Dc_GetFollowButton($dc['popover']['user_id']); ?></div>
<div class="user-button message-button"><?php echo Dc_GetMessageButton($dc['popover']['user_id']); ?></div>
<?php } ?>
<?php if(Dc_IsStudent($dc['popover']['user_id']) == false) { ?>
<?php echo $dc['lang']['student_contact_warning']; ?>
<?php } ?>
<?php } ?>
<?php if($dc['user']['student'] !== 1){ ?>
<?php if(Dc_IsStudent($dc['popover']['user_id']) == false){ ?>
<div class="user-button user-follow-button"><?php echo Dc_GetFollowButton($dc['popover']['user_id']); ?></div>
<div class="user-button message-button"><?php echo Dc_GetMessageButton($dc['popover']['user_id']); ?></div>
<?php } ?>
<?php if(Dc_IsStudent($dc['popover']['user_id']) == true) { ?>
<?php echo $dc['lang']['student_contact_warning']; ?>
<?php } ?>
<?php } ?>
Do yourself a favour and start to use variables for repeated functions, and look up PHP's HereDoc to allow you to simplify your code. I think you'll agree the following is clearer.
The question now is what values you expect in your conditions. Run the following and check that the outputted IsStudent and Student are what you expect.
<?php
$Student=$dc['user']['student'];
$IsStudent=Dc_IsStudent($dc['popover']['user_id']);
$Dc_FollowBut=Dc_GetFollowButton($dc['popover']['user_id']);
$Dc_MessageBut=Dc_GetMessageButton($dc['popover']['user_id']);
echo"IsStudent: $IsStudent<br>";
echo"Student: $Student<br>";
if($Student!=0){
if($IsStudent==true){
echo<<<EOC
<div class="user-button user-follow-button">$Dc_FollowBut</div>
<div class="user-button message-button">$Dc_MessageBut</div>
EOC;
}else{
echo $dc['lang']['student_contact_warning'];
}
}
if($Student!=1){
if($IsStudent==false){
echo<<<EOC
<div class="user-button user-follow-button">$Dc_FollowBut</div>
<div class="user-button message-button">$Dc_MessageBut</div>
EOC;
}else{
echo $dc['lang']['student_contact_warning'];
}
}
?>
<?php
if($dc['user']['student'] != 0){
if(Dc_IsStudent($dc['popover']['user_id']) == true){
echo '<div class="user-button user-follow-button">'. Dc_GetFollowButton($dc['popover']['user_id']) .'</div>';
echo '<div class="user-button message-button">'. Dc_GetMessageButton($dc['popover']['user_id']) .'</div>';
} else {
echo $dc['lang']['student_contact_warning'];
}
} else if($dc['user']['student'] != 1){
if(Dc_IsStudent($dc['popover']['user_id']) == false){
echo '<div class="user-button user-follow-button">'. Dc_GetFollowButton($dc['popover']['user_id']) .'</div>';
echo '<div class="user-button message-button">'. Dc_GetMessageButton($dc['popover']['user_id']) .'</div>';
} else {
echo $dc['lang']['student_contact_warning'];
}
}
?>
Try putting it in one block, rather than 2 seperate blocks. If-else blocks are meant like that. I would prefer using cases here, though i tried cleaning this up a bit for you to see whats going on.
I agree with #jbes in the other awnser that you should use variables, to make things a lot easier to read. i didn't do this, but i totally agree on that part.
A typo can be made quickly if you constantly run only if blocks, with else, you can point to a different actions in the same if, without closing the complete block. Now I don't know if $dc['user']['student'] can only be 0 or 1, but else you can toss away the complete else-if statement and just change it to else to make it more cleaner. Also to check if not 0 leaves open for a lot of interpretation, what if the value is 2 or 48644. it would always trigger both blocks, so you may want to swap it around to check if the value equals 1 or 0.
I hope this points you in the right direction
I would first make the PHP code more clear. Then you will see that you didn't close some tags.
<?php
if ($dc['user']['student'] !== 0) {
if (Dc_IsStudent($dc['popover']['user_id']) == true) {
echo '<div class="user-button user-follow-button">';
echo Dc_GetFollowButton ($dc['popover']['user_id']);
echo '</div>' . "\n";
echo '<div class="user-button message-button">';
echo Dc_GetMessageButton($dc['popover']['user_id']);
echo '</div>' . "\n";
} else {
echo $dc['lang']['student_contact_warning'];
}
}
if ($dc['user']['student'] !== 1){
if (Dc_IsStudent($dc['popover']['user_id']) == false){
echo '<div class="user-button user-follow-button">';
echo Dc_GetFollowButton($dc['popover']['user_id']);
echo '</div>' . "\n";
echo '<div class="user-button message-button">';
echo Dc_GetMessageButton($dc['popover']['user_id']);
echo '</div>' . "\n";
} else {
echo $dc['lang']['student_contact_warning'];
}
}
?>
Now we can start analyzing the code.

Check if the number of element is equal to a specific number PHP

From the image below, you can see there is a empty space in second row (red rectangular), by right it should filling up the empty space. This is happening because the first image title is longer than others.
I know by using HTML code, I can use clear: both; and put under the first row to solve it. But my info is read from database. Following is my php and mysql code, I have simplified it, please ignore the method I use to display the image.
$selectSQL="SELECT *, DATE_FORMAT(published_date,'%d %M %Y') AS eventDate FROM media";
while($rows=mysql_fetch_array($selectSQL)){
<div style="float:left">
<img src="load_image.php?id=<?php echo $rows["id"]; ?>" width="150px" height="212px">
<div><?php echo $rows["title"]; ?></div>]
<div><?php echo $rows["eventDate"]; ?></div>
</div>
}
I have one solution, which is compare the number of element = 5. Something like the following code. But I'm not sure how to check it the number of element. Please advice or please suggest me if you have another solutions. Thanks!
if($num_element==5){
echo '<div class="clear"></div>';
}
$ i = 0;
while($rows=mysql_fetch_array($selectSQL)){
<div style="float:left">
<img src="load_image.php?id=<?php echo $rows["id"]; ?>" width="150px" height="212px">
<div><?php echo $rows["title"]; ?></div>]
<div><?php echo $rows["eventDate"]; ?></div>
</div>
$i++;
if($i % 5 == 0){
echo '<div class="clear"></div>';
}
}
you can try this code to check the number of items totally displayed and after 5 elements it will print a clear div
You can use substr() to concat your title when it is very long. you can try it like this:
while($rows=mysql_fetch_array($selectSQL)){
<div style="float:left">
<img src="load_image.php?id=<?php echo $rows["id"]; ?>" width="150px" height="212px">
<div title="<?php echo $rows["title"];?>">
<?php if(strlen($rows["title"]) > 6){
echo substr($rows["title"],0, 6).'...';
}else{
echo $rows["title"];
} ?>
</div>
<div><?php echo $rows["eventDate"]; ?></div>
</div>
}
With this code you can customize the length of the words in your title.

How to insert an end div inside a PHP foreach loop when count meets a specific value

I have a page that lists a set of questions and answers that are held on a database. Because these pages will be printed off on to A4, the questions and answers must fit within the page. However, because of the way the system is used, the answers are quite lengthy and over run a set dimension for an A4 piece of paper.
I have worked out that for my specific need, each A4 piece of paper will have a word limit of 680. The test data I am using has exceeded this, and currently stands are 972 words in total.
Currently this is the code I am using (be aware that there is an individual word count recorded for every individual answer and every individual question):
<div class="page" style="page-break-before: always;">
<div class="smallheading">
<h2>Management Information</h2>
</div>
<div class="content v2">
<?php
$totalCharacters = 0;
$totalcharacters1 = 0;
$totalcharacters2 = 0;
foreach($sqsi as $si) {
$totalcharacters1 += $si['Swmpquestion']['wordcount'] + $si['Swmpanswer']['wordcount'];
} foreach ($sqsicust as $wr) {
$totalcharacters2 += $wr['Swmpanswer']['wordcount'] + $wr['Swmpanswer']['cqwordcount'];
}
$totalCharacters = $totalcharacters1 + $totalcharacters2;
?>
<?php foreach($sqsi as $si) { ?>
<p><strong><?php echo $si['Swmpquestion']['question']; ?></strong></p>
<p><?php echo $si['Swmpanswer']['answer']; ?></p>
<hr />
<?php } foreach($sqsicust as $wr) { ?>
<p><strong><?php echo $wr['Swmpanswer']['custquestion']; ?></strong></p>
<p><?php echo $si['Swmpanswer']['answer']; ?></p>
<hr />
<?php } ?>
</div>
What I want to achieve is that while the PHP script goes through it's foreach, every time the questions and answers in that foreach reach 680 words an end and start div would be inserted, so the long list of data would be split up properly. How can I achieve this?
If i understood you correctly, then you just need to assign the variable to be iterated and make a comparison against it in your loop.
foreach($sqsi as $i => $si) { // note $i =>
if($i == 679) echo '</div><div>'; ?>
<p><strong><?php echo $si['Swmpquestion']['question']; ?></strong></p>
<p><?php echo $si['Swmpanswer']['answer']; ?></p>
<hr />
<?php }
You said you're already keeping a count of words, so why not just use a simple if statement in the second 2 foreach loops? Instead of counting the words in the first two foreach loops like you're doing. Keep track of how many words in the 2nd two foreach loops and then a simple if statement will do the trick. Something like this should work if I understood you correctly:
<div class="page" style="page-break-before: always;">
<div class="smallheading">
<h2>Management Information</h2>
</div>
<div class="content v2">
<?php
$totalCharacters = 0;
$totalcharacters1 = 0;
$totalcharacters2 = 0;
foreach($sqsi as $si) {
$totalcharacters1 += $si['Swmpquestion']['wordcount'] + $si['Swmpanswer'] ['wordcount'];
} foreach ($sqsicust as $wr) {
$totalcharacters2 += $wr['Swmpanswer']['wordcount'] + $wr['Swmpanswer']['cqwordcount'];
}
$totalCharacters = $totalcharacters1 + $totalcharacters2;
?>
<?php foreach($sqsi as $si) {
$totalcharacters1 = $si['Swmpquestion']['wordcount'] + $si['Swmpanswer'] ['wordcount']
if($totalcharacters1 == 680){
echo "</div>";
echo "<div class="content v2">";
$totalcharacters1=0;
}
?>
<p><strong><?php echo $si['Swmpquestion']['question']; ?></strong></p>
<p><?php echo $si['Swmpanswer']['answer']; ?></p>
<hr />
<?php } foreach($sqsicust as $wr) {
$totalcharacters2 += $wr['Swmpanswer']['wordcount'] + $wr['Swmpanswer']['cqwordcount'];
if($totalcharacters2 == 680){
echo "</div>";
echo "<div class="content v2">";
$totalcharacters2=0;
}
?>
<p><strong><?php echo $wr['Swmpanswer']['custquestion']; ?></strong></p>
<p><?php echo $si['Swmpanswer']['answer']; ?></p>
<hr />
<?php } ?>
</div>
add an $i=0; //a starting point
and an $qtyToLpThru=x; //ie every 25 iterations
before the foreach.
within foreach add just after the first { an if statement..
foreach(){
if (is_int($i/$qtyToLpThru)) && $i!=0) {
echo '</div><div>';
}
$i++;
}
then add an $i++; just before the last }.
your iteration will increment the $i and you'll write your end and open div every time the if statement processes true.

If statement to not show div / h2

This for each / if statement displays changes, and then right below it it displays the changes made.
I am trying to write an if statement that tells it not to show the h2 and the #change_box if there are no changes.
Help would be greatly appreciated.
<h2 class="changes"> Changes: </h2>
<div id="change_box">
<? foreach ($audit['Events'] as $event):?>
<?if ( $event['Type'] != 'Comment'):?>
<span class="field">
<?= $event['Field']?>
</span>:
<?= $event['Value'] ?>
<?=($event['Previous'])?>
<?endif?>
<?endforeach?>
</div>
<?php
if ($changes) { // You'll have to set this variable
//Echo all of your HTML
else {
//Echo the stuff you'd rather show if they didn't change anything
}
?>
To give you an idea of how I'd write your code
<?php
if ($changes) {
echo '<h2 class="changes">Changes:</h2>';
echo '<div id="change_box">';
foreach ($audit['Events'] as $event) {
if ($event['Type'] != 'Comment') {
echo $event['Field'] . </span> . $event['Value'] . $event['Previous'];
}
}
echo "</div>"
}
?>
You could wrap your code with an if like
if(count($audit['Events'])>0)
{
//Your code
}
Wny do you open and close php tags every time? Would be better to make everything in PHP and echo whenever you want to print HTML code.
<?php
echo "<h2 class=\"changes\"> Changes: </h2>";
echo "<div id=\"change_box\">";
foreach ($audit['Events'] as $event) {
if ( $event['Type'] != 'Comment') {
echo "<span class=\"field\">".$event['Field']."</span>";
echo $event['Value'];
echo "(".$event['Previous'] .")";
}
}
echo "</div>";
?>
please make space after each <? and make sure you enabled short tags
<?php if(is_array($audit['Events']) && $audit['Events']):?>
<h2 class="changes"> Changes: </h2>
<div id="change_box">
<?php foreach ($audit['Events'] as $event):?>
<?php if ( $event['Type'] != 'Comment'):?>
<span class="field">
<?php echo $event['Field'];?>
</span>:
<?php echo $event['Value']; ?>
<?php echo $event['Previous'];?>
<?php endif;?>
<?php endforeach;endif;?>
</div>

Offset PHP array results

I am looking to offset a group of PHP array results to create multiple rows of data.
For example, the first row will contain the first four array results, with the second row displaying results 5-8 and the third row containing results 9-12.
Currently, I am printing out all 12 in one list, however I'd like a bit more display control (i.e. ordering the results into columns which I can style independent of each), hence why I'd like to offset the results.
My current PHP is below:
<?php
if (empty($tmdb_cast['cast'])) {
} else {?>
<section class="cast">
<p class="title">Cast</p>
<ul class="section_body"><?php
foreach($tmdb_cast['cast'] as $key => $castMember){
if ($key < 12) {?>
<li class="actor_instance clearfix"><?php
if ($castMember['profile_path'] != '') {?>
<img src="http://cf2.imgobject.com/t/p/w45<?php echo $castMember['profile_path']; ?>" class="actor_image pull-left" alt="<?php echo $castMember['name']; ?>" title="<?php echo $castMember['name']; ?>" /><?php
} else {?>
<img src="assets/images/castpic_unavailable.png" class="actor_image pull-left" alt="No image available" title="No image available" /><?php
}?>
<p class="actor"><?php echo $castMember['character']; ?> - <?php echo $castMember['name']; ?></p>
</li><?php
}
}?>
<div class="morecast pull-right">[...view all cast]</div>
</ul>
</section><?php
}?>
P.S. Apologies for how I've formatted the code in the above block - I'm still not 100% sure how to make it look "nice" on StackOverflow.
Use array_chunk to break a single dimension array into a 2D array. Then you can loop through each chunk, and then each result, to get that "offset" effect between them.
$chunks = array_chunk($tmdb_cast['cast'], 4); // 4 here, is the number you want each group to have
foreach($chunks as $key => $chunk)
{
foreach($chunk as $castMember)
{
//display castMember here
}
// add code between groups of 4 cast members here
}
First: mixing php and html this way is a very bad habbit... one day you will have to maintain your code and that day you will vomit all over your desk because you mixed different languages in one file...
That being said..
and without creating a new array:
foreach($tmdb_cast['cast'] as $key => $castMember)
{
if ($key < 12)
{
// your code goes here
// if key is 3, or 7 the code below will close the listcontainer and open a new one...
if( ($key+1)%4 == 0 AND $key <11)
echo '</ul> <ul class="section_body">';
}
}
Also replace this:
if (empty($tmdb_cast['cast']))
{
}
else {
with this:
if (!empty($tmdb_cast['cast']))
{
I'm not entirely sure what you're looking for but here's how I would format your code. Alternative syntax for 'if' is a little more readable, and the use of for loops instead of a foreach will give you the control over row numbers you say you're looking for.
<?php if( ! empty($tmdb_cast['cast'])): ?>
<section class="cast">
<p class="title">Cast</p>
<ul class="section_body">
<?php
for($i = 0; $i < 12; $i++):
$castMember = $tmdb_cast['cast'][$i];
?>
<li class="actor_instance clearfix">
<?php if($castMember['profile_path'] != ''): ?>
<img src="http://cf2.imgobject.com/t/p/w45<?php echo $castMember['profile_path']; ?>" class="actor_image pull-left" alt="<?php echo $castMember['name']; ?>" title="<?php echo $castMember['name']; ?>" />
<?php else: ?>
<img src="assets/images/castpic_unavailable.png" class="actor_image pull-left" alt="No image available" title="No image available" />
<?php endif; ?>
<p class="actor"><?php echo $castMember['character']; ?> - <?php echo $castMember['name']; ?></p>
</li>
<?php endfor; ?>
<div class="morecast pull-right">[...view all cast]</div>
</ul>
</section>
<?php endif; ?>

Categories