Jeffro Posted April 20, 2011 Share Posted April 20, 2011 I'm printing some mysql results to a table and sometimes I have rows with no results so they never get counted... which results in an ugly looking parenthesis on my page with nothing it (). For these times, I'd like to print a zero. How can I rewrite the following to achieve this? if($row['mycount'] does not exist) { $row['mycount'] = '0'; } Link to comment https://forums.phpfreaks.com/topic/234202-how-do-i-write-a-0-count-if-a-row-doesnt-exist/ Share on other sites More sharing options...
spiderwell Posted April 20, 2011 Share Posted April 20, 2011 when you say $row['mycount'] does not exist do you mean its value is NULL? Link to comment https://forums.phpfreaks.com/topic/234202-how-do-i-write-a-0-count-if-a-row-doesnt-exist/#findComment-1203785 Share on other sites More sharing options...
DavidAM Posted April 20, 2011 Share Posted April 20, 2011 if (empty($row['mycount'])) { $row['mycount'] = '0'; } Should do the trick. If the element does not exist in the array, or if it is false, null, or zero; empty() will be true. You could also do it using the ternary operator in the output: echo 'The count is: ' . (empty($row['mycount']) ? '0' : $row['mycount']); Link to comment https://forums.phpfreaks.com/topic/234202-how-do-i-write-a-0-count-if-a-row-doesnt-exist/#findComment-1203788 Share on other sites More sharing options...
Jeffro Posted April 20, 2011 Author Share Posted April 20, 2011 Hmmm... seems like that should have worked, but it didn't seem to do anything. When the row doesn't exist, it still won't assign a zero. Here's my full code: $query = "SELECT SUBSTR(url,8,INSTR(url,'.')- as cityname, COUNT(*) as citycount FROM cities GROUP BY SUBSTR(url,8,INSTR(url,'.')-"; $result = mysql_query($query) or die(mysql_error()); $data = array(); while($row = mysql_fetch_array($result)) { $data[$row['cityname']] = $row['citycount']; } Later on, I'm calling the city names in my hyperlinks, like so: <a href="/city/ausin/">Austin</a> (<?php echo $data['austin']; ?>)<br> <a href="/city/dallas/">Dallas</a> (<?php echo $data['dallas']; ?>)<br> <a href="/city/miami/">Miami</a> (<?php echo $data['miami']; ?>)<br> This produces a result set such as: Austin (9) Dallas (4) Miami () <-- where () should read (0) Link to comment https://forums.phpfreaks.com/topic/234202-how-do-i-write-a-0-count-if-a-row-doesnt-exist/#findComment-1203799 Share on other sites More sharing options...
The Little Guy Posted April 20, 2011 Share Posted April 20, 2011 Use type casting: $count = 0; while($row = mysql_fetch_array($result)) { $data[$row['cityname']] = (int)$row['citycount']; } Link to comment https://forums.phpfreaks.com/topic/234202-how-do-i-write-a-0-count-if-a-row-doesnt-exist/#findComment-1203818 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.