Joss Posted February 22, 2013 Posted February 22, 2013 I am using a file field that has two files in it. I want to check anything is in it before displaying it, so: if($page->Files){ echo "<div class='attachments'>"; echo "<h3>Attachements</h3>"; foreach($page->Files as $file) { echo "<p><a href='{$file->url}'>{$file->description} - {$file->name}</a></p>"; } echo "</div>"; } The problem is, even if I have no files loaded to the page, the DIV still displays. I have been up half the night with a bad shoulder, so this is probably just my brain dying help! Joss
Wanze Posted February 22, 2013 Posted February 22, 2013 if (count($page->Files)) { //... } Because $page->Files is a WireArray and that is casted to "true" by PHP 1
Joss Posted February 22, 2013 Author Posted February 22, 2013 Doh! ... I knew that! Thanks, Wanze More sleep needed! 1
Wanze Posted February 22, 2013 Posted February 22, 2013 Doh! ... I knew that! Thanks, Wanze More sleep needed! Since I know Pw my average sleep time's getting shorter and shorter. Yesterday I went to bed @ 23.00, thinking around Pw-Projects and ideas till midnight and finally realized I couldn't sleep – standing up again to do some coding on a new module till 01.30. 3
Joss Posted February 22, 2013 Author Posted February 22, 2013 Oh, you are so right! Just need to try and get some cash for all these hours! 1
Pete Posted February 23, 2013 Posted February 23, 2013 I think the preferred method is actually: if ($page->files->count() > 0) { Though I can't for the life of me remember why there was a performance benefit to using PW's method above, I'm sure there definitely was one... possibly because the count is already part of what's loaded into memory in the PageArray and you're not counting things again unnecessarily. Or I could be talking utter rubbish. Who knows
diogo Posted February 23, 2013 Posted February 23, 2013 Pete, I have the idea that count($a) is better for performance than $a->count()
ryan Posted February 25, 2013 Posted February 25, 2013 There is no performance benefit to count($a) vs. $a->count(). They both end up going through the same route. The reason that you can do count($a) on any WireArray derived types is that they implement PHP/SPL's Countable interface. I kind of like the count($a) syntax because it's consistent with array counting syntax.
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now