I would like to surround this entire block of code in a try/catch since its causing an error when there is nothing in the grid array. Whats the best way to do this?
<?php foreach ($grid->result() as $idx => $row): ?> <?php if ($idx % 3 == 2): ?>
<div class="img_grid_3"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php else: ?>
<div class="img_grid"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php endif; ?>
<?php endforeach; ?>
Thanks
Maybe Im missing the point but why dont you test $grid before doing the foreach?
<?php if($grid): ?>
.... foreach ....
<?php endif; ?>
If I got you right, you're looking for the # error suppression operator. If you pass an empty array to foreach, you'll get a PHP warning, you can't catch this with a try/catch block.
<?php #foreach ($grid->result() as $idx => $row): ?>
<?php if ($idx % 3 == 2): ?>
<div class="img_grid_3"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php else: ?>
<div class="img_grid"><img src="/images/thumb/<?= $row->images_name; ?>" /></div>
<?php endif; ?>
<?php endforeach; ?>
It's possible to use a try catch block with html contents too, but it will obviously only catch Exceptions.
Note that it's cleaner to check wheter the array is empty or not before you use it in a foreach block.
foreach will not produce an error if the array is empty.
So either $grid is not an object, or result() is returning a non-array like false or null. If the former, surround the foreach with if ($grid), of the latter, than use if (!empty($grid->result()))
Related
Can anyone please help me wrap the condition inside another condition in php.
I have this code #1 that I want to be inside code #2.
Here's code #1
<?php if( get_field('highlights') ): ?>
<div class="overview">
<h3>Quick Overview</h3>
<?php the_field('highlights'); ?>
</div>
<?php endif; ?>
Here's code #2
<?php if(strstr($_SERVER['HTTP_REFERER'],'www.example.com'))
{
echo '**CODE #1 should be placed here**';
}
?>
Sorry, I don't haev any knowledge in PHP.
Wrapping code 1 inside code 2
After several trial and error, here's what I have to make it work. Please correct me if there's something wrong or to improve.
<?php if (strstr($_SERVER['HTTP_REFERER'], 'www.google.com')){ ?>
<?php if( get_field('highlights') ):?>
<div class="overview">
<h3>Quick Overview</h3>
<?php the_field('highlights'); ?>
</div>
<?php endif; ?>
<?php } ?>
This should work in theory. Though I'm unsure what the highlights field is for.
<?php
if(strstr($_SERVER['HTTP_REFERER'],'www.example.com')){
if( get_field('highlights') ){ ?>
<div class="overview">
<h3>Quick Overview</h3>
<?php the_field('highlights'); ?>
</div>
<?php
}
}
?>
You may want to replace <?php the_field('highlights'); ?> with something like <?=highlight ?> and iterate through the highlights in a loop. That depends on the situation though.
I am learning PHP from the book "Murach PHP and MySQL 2nd Edition" and I came across this code which I don't fully understand...
<select name="productkey">
<?php foreach ($products as $key => $product):
$cost = number_format($product['cost'], 2);
$name = $product['name'];
$item = $name . ' ($)' . $cost . ')';
?>
<option value="<?php echo $key; ?>"> <?php echo $item; ?></option>
<?php endforeach; ?>
</select>
Why are there instructions after the colon (:) at the start of the foreach loop??
I read that after the colon there should be "?>" and then the instructions to execute and then at end "" to mark the end of the foreach loop...
Please explain this AND IF I WRITE THE LINES STARTING WITH $cost,$name and $item after <?php foreach ($products as $key => $product): ?> would the code still work???
yes it would still work : is the same as { but you have to write endforeach at the end of your foreach it does the same thing more info check out this page
documentation
: called an Alternative Syntax For Control Structures.
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
It allows you to omit braces {} from a foreach to make it look cleaner and its mostly used, within templates.
The colon is an alternative to using brackets.
This:
foreach (...) :
#execute Code in loop
endforeach;
is the same as this:
foreach (...) {
#execute Code in loop
}
The alternative syntax is mainly for use with mixed html content. The main advantage is say you have something like this
<?php if( $var ){ ?>
<!-- some html here -->
<?php foreach( $var as $v ){ ?>
<!-- some html here -->
<?php if( $v=='foo'){ ?>
<!-- some html here -->
<?php } ?>
<!-- some html here -->
<?php } ?>
<!-- some html here -->
<?php } ?>
You quickly wind up with a mess of } everywhere, compare to this
<?php if( $var ): ?>
<!-- some html here -->
<?php foreach( $var as $v ): ?>
<!-- some html here -->
<?php if( $v=='foo'): ?>
<!-- some html here -->
<?php endif; ?>
<!-- some html here -->
<?php endforeach; ?>
<!-- some html here -->
<?php endif; ?>
This is a small example so I don't think if fully shows the issue, but it's much easier to where the if blocks end and the foreach ends even in this.
Now multiple that by about 200 lines of mixed content. Otherwise you can look at it as the : is a { and the end{blocktype}; is the }
Personally I never use it ( except on SO ), because I don't mix HTML and PHP in my code.
cheers.
As you said it normally called PHP alternate syntax for control structure. You can read in more depth in that article:
Alternate Syntax is normally used when we need to mix-up HTML inside PHP. In your code:
<select name="productkey">
<?php foreach ($products as $key => $product):
$cost = number_format($product['cost'], 2);
$name = $product['name'];
$item = $name . ' ($)' . $cost . ')';
?>
<option value="<?php echo $key; ?>"> <?php echo $item; ?></option>
<?php endforeach; ?>
You can see you have a option inside foreach. In this type of case it's better to use alternate syntax. We can use the alternate syntax for if else and switch case as well.
I would like to use a PHP echo as a condition inside a PHP if statement.
The aim is to have the list of blog articles written by John Doe, displayed on his biography page.
It worked when I directly wrote the author's name in the if condition:
<!-- current page: biography page -->
<div id="list_of_articles_by_John_Doe">
<?php foreach(page('magazine')->children() as $article): ?>
<?php if($article->author() == 'John Doe'): ?>
<p><?php echo $article->title() ?></p>
<?php endif ?>
<?php endforeach ?>
</div>
But I would like to automate the process, for each writer's biography page to have their own list of articles.
I tried to have as a condition the author of the current biography page ($page):
<!-- current page: biography page -->
<div id="automatic_list_of_articles">
<?php foreach(page('magazine')->children() as $article): ?>
<?php if($article->author() == $page->author()): ?>
<p><?php echo $article->title() ?></p>
<?php endif ?>
<?php endforeach ?>
</div>
but it makes another issue: it does not work because inside the foreach statement, $page->author() (condition in the if statement) does not echo the author once, but one time for each page('magazine')->children() as $article.
The condition if($article->author() == $page->author()) does not work in this case, as $page->author() is not strictly the writer's name.
I'm wondering how to call $page->author() to echo the writer's name only once, when inside the foreach statement.
What could be an option is to save all author within an array
// if article->author() isn't within the array
$authors[] == $article->author();
After that you could go as the following:
<?php foreach($authors as $author){ ?>
<?php foreach(page('magazine')->children() as $article): ?>
<?php if($article->author() == $author()): ?>
<p><?php echo $article->title() ?></p>
<?php endif ?>
<?php endforeach ?>
<?php } ?>
That should work, even if you must do 2 foreachs
<?php if( $article->author() == $page->author() ) { ?>
<p><?php echo $article->title(); ?></p>
<?php } ?>
should work, but you can also try
<?php
if( $article->author() == $page->author() ) {
echo "\n<p>", $article->title(), "</p>\n";
}
?>
which to me looks "cleaner"; but you'd have to have a look for missing whitespaces
I suggest trying to set it equal too a variable and then using that variable in the if statement.
<?php foreach(page('magazine')->children() as $article): ?>
<?php $condition = $page->author()?>
<?php if($article->author() == $condition ?>'): ?>
echo "\n<p>", $article->title(), "</p>\n";
<?php endif ?>
<?php endforeach ?>
I am not sure if my syntax is correct but i think it is something along them lines.
You cannot use echo in condition because it is special language construct that sends given contents to the output stream and it returns no value.
Are you sure you shouldn't have this?
<div id="automatic_list_of_articles">
<?php $page = page('magazine'); ?>
<?php foreach($page->children() as $article): ?>
<?php if($article->author() == $page->author()): ?>
<p><?php echo $article->title() ?></p>
<?php endif ?>
<?php endforeach ?>
</div>
I have reconstructed an approximation of what looks to be your data, and you can see it working at the link below. It correctly echo's multiple article titles.
Working example:
http://ideone.com/jvLVhF
In this example you can see the PHP as above works correctly, and it is likely a data issue (ie. you should perhaps be using $page and not calling a function in the foreach statement).
I´ve got the following code and when I paste the code to my page, I get a white page, can you guys help me?
PHP
<?php $strRendersettings = ($this->settings)? 'settings' : 'view'; ?><?php if (count($this->data)): ?>
<ul>
<?php
switch($_SERVER['HTTP_HOST'])
{
case ("www.domain.de"):
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home"><a href=""; ?>" ><strong><?php echo $arrItem['text']['new_docs_titel']; ?>:</strong><br>
<p><?php echo $arrItem['text']['new_docs_Text']; ?></p></a>
</li>
<?php
break;
case ("www.domain.com"):
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home"><a href=""; ?>" ><strong><?php echo $arrItem['text']['new_docs_titel']; ?>:</strong><br>
<p><?php echo $arrItem['text']['new_docs_Text']; ?></p></a>
</li>
<?php
break;
case ("www.domain.fr"):
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home"><a href=""; ?>" ><strong><?php echo $arrItem['text']['new_docs_titel']; ?>:</strong><br>
<p><?php echo $arrItem['text']['new_docs_Text']; ?></p></a>
</li>
<?php
break;
}
?>
<?php endforeach; ?>
</ul>
<?php else: ?>
<?php endif; ?>
I need the code because of some different top level domains.
Thanks :)
The porblem is that you never end you foreach loops.
You should end each foreach: loop with endforeach;. Now you have 3 loops and only one closing endforeach;
For example this code works without a problem:
<?php
$array = [1=>2, 3=> 4];
$array2 = [5=>6,7=>8];
foreach ($array as $k => $v):
foreach ($array2 as $i => $j):
echo $i.' '.$j."<br />";
endforeach;
endforeach;
while the following doesn't:
<?php
$array = [1=>2, 3=> 4];
$array2 = [5=>6,7=>8];
foreach ($array as $k => $v):
foreach ($array2 as $i => $j):
echo $i.' '.$j."<br />";
//endforeach;
endforeach;
I advice you also to add at the beginning of your PHP file:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
to have all warnings and error displayed. Of course on production you should disable error reporting
It looks like you're breaking the foreach loop with the break of the switch. You should end the foreach inside each case of the switch.
See you PHP error log for error messages. When there is a parse error, the page is shown blank, and the error message goes to the PHP error log.
In your code, <?php endforeach; ?> appears to be outside the switch. I guess each foreach should have its own endforeach before the switch's break.
Correct me if I'm wrong, but you are doing the exact same thing for each of the three scenarios. I would alter my code to this:
<?php $strRendersettings = ($this->settings)? 'settings' : 'view'; ?>
<?php if (count($this->data)): ?>
<ul>
<?php
switch($_SERVER['HTTP_HOST'])
{
case "www.domain.de":
case "www.domain.com":
case "www.domain.fr":
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home">
<a href="">
<strong>
<?php echo $arrItem['text']['new_docs_titel']; ?>:
</strong><br>
<p>
<?php echo $arrItem['text']['new_docs_Text']; ?>
</p>
</a>
</li>
<?php
endforeach;
break;
}?>
</ul>
You need to add endforeach statement before every break statement. Add that and your error will get sloved.
Hope this help :)
Im writing a foreach loop for my view using the alternative syntax, to get a piece of html like this
<h3>My Post</h3>
Ive used the line below, but it seems awfully clunky with all the concatenation.
<?php
foreach ($index_posts as $post):
?>
<h3><?= "" . $post['title'] . ""; ?></h3>
<?php
endforeach;
?>
Ive also tried writing it like this :
<?= "<a href='post.php/?id=$post['id']'>$post['title']</a>"; ?>
But it shows errors when written in sublime text 2 around the ['id'] and ['title'] any ideas why this is, as they are single quotes ?
Is there another way i could write this that is cleaner ?
You could just do:
<?php foreach ($index_posts as $post): ?>
<h3>
<a href="post.php?id=<?php echo $post['id']; ?>">
<?php echo $post['title']; ?>
</a>
</h3>
<?php endforeach; ?>
The reason Sublime is showing an error when you do this
<?= "<a href='post.php/?id=$post['id']'>$post['title']</a>"; ?>
is due to the fact that it's a syntax error as you can't have complex variables (like array values with strings for keys) interpolated into a string directly like this. You need to wrap them in {}
<?= "<a href='post.php/?id={$post['id']}'>{$post['title']}</a>"; ?>
Alternatively, you could use:
foreach ($posts as $post) {
printf('%s', $post['id'], $post['title']);
}
<?php foreach ($index_posts as $post): ?>
<h3>
<a href='post.php/?id=<?=$post['id']?>'>
<?=$post['title']?>
</a>
</h3>
<?php endforeach; ?>
Keeping it to HTML whenever you can; I much prefer to not 'echo' out HTML unless needed, although this question really quite about preference. Afterall, PHP is an templating language!
Gotta help a fellow sam...
<?php echo "<h3>{$post['title']}</h3>"; ?>