completeamateur Posted October 13, 2008 Share Posted October 13, 2008 Hi, I am running a loop to generate the meta tags for a page, but if the database contains no meta tags, php throws a warning... Warning: Invalid argument supplied for foreach() in /Library/WebServer/Documents/villa4life/application/layouts/layout.phtml on line 6 foreach($this->metadata as $metadata) Is there anyway to prevent this? TIA Link to comment https://forums.phpfreaks.com/topic/128271-dont-perform-a-loop-when-value-is-empty/ Share on other sites More sharing options...
F1Fan Posted October 13, 2008 Share Posted October 13, 2008 <?php $var = $this->metadata; if (is_array($var)){ foreach($var as $metadata)... Link to comment https://forums.phpfreaks.com/topic/128271-dont-perform-a-loop-when-value-is-empty/#findComment-664374 Share on other sites More sharing options...
Stooney Posted October 13, 2008 Share Posted October 13, 2008 <?php if(is_array($this->metadata) && count($this->metadata)>0){ foreach($this->metadata as $metadata){ //Whatever happens } } ?> Link to comment https://forums.phpfreaks.com/topic/128271-dont-perform-a-loop-when-value-is-empty/#findComment-664376 Share on other sites More sharing options...
gizmola Posted October 13, 2008 Share Posted October 13, 2008 you can check prior to the loop, by comparing $this->metadata to NULL, for example: if ($this->metadata != null) { //Do your foreach //etc You can also turn down the errorlevel so that it doesn't include warnings, if there's no particular logic concern. Of course on a production server you should not have error reporting on anyways, as you will want to log errors instead. Link to comment https://forums.phpfreaks.com/topic/128271-dont-perform-a-loop-when-value-is-empty/#findComment-664377 Share on other sites More sharing options...
Acs Posted October 13, 2008 Share Posted October 13, 2008 if ($this->metadata) run foreach or if it returns a mixed value: if (is_array($this->metadata)) run foreach Link to comment https://forums.phpfreaks.com/topic/128271-dont-perform-a-loop-when-value-is-empty/#findComment-664378 Share on other sites More sharing options...
completeamateur Posted October 13, 2008 Author Share Posted October 13, 2008 Cheers guys! Link to comment https://forums.phpfreaks.com/topic/128271-dont-perform-a-loop-when-value-is-empty/#findComment-664385 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.