Thursday, December 31st

In my favorite programming language Ruby, there are many intuitive methods to use on Arrays. Unfortunately, in my experience, PHP doesn't have the same intuition in many cases. Since my website runs on Processwire, a PHP-based Content Management System, I am often in contact with this very issue.

So here is a common thing, the need to select the first or last element of an array. In Ruby I would do it like so:

arr = [1, 2, 3, 4, 5, 6]
arr.first #=> 1
arr.last #=> 6

And that's it! Thank you intuitive methods!

This would have been helpful when I wanted to list the categories for each Blog Post or Tutorial Post. After each $category, I would want to echo ", ";, except of course on the last item. So here is how to acheive the .last method in PHP:

$catCount = 0;
$catTotal = count($page->postCategories);
foreach ($page->postCategories as $category) {
echo $category->postCategory;
if ($catCount != $catTotal) echo ", ";

So you can see I:

  1. Created a simple Iteration Variable $catCount.
  2. Set $catCount to 0.
  3. For each Array Item I added 1 to $catCount.
  4. I compared the total number of Array Items via the PHP count(); method, saved in the variable $catTotal, with the current value of our Iteration Variable $catCount.
  5. If $catTotal is the same as $catCount, you've found the last Array Item!

I have nothing inherently against PHP (that should be obvious from my use of Processwire and some possible future Laravel Web Apps), but I sure wish there was a last($arr); method!!!