Hackerrank with PHP: 2D Array - DS

I've been doing coding challenges on Hackerrank after not doing so great on a code test. They definitely get you thinking outside the normal, everyday work situations I face during my full-time job. As I find solutions, I am posting them here in case someone else is stuck. I code primarily in PHP, so that's what my solutions will be in.

Here's the problem below.

There are 16 hourglasses in $arr, and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in $arr, then print the maximum hourglass sum.

Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.

hourglassSum has the following parameter(s):

arr: an array of integers

// Complete the hourglassSum function below.
function hourglassSum($arr) {
    for($i = 0; $i <= count($arr) - 3; $i++) {
        for($j = 0; $j <= count($arr[$i]) - 3; $j++) {
            $result[] = intval($arr[$i][$j] + $arr[$i][$j+1] + $arr[$i][$j+2]
                + $arr[$i+1][$j+1]
                + $arr[$i+2][$j] + $arr[$i+2][$j+1] + $arr[$i+2][$j+2]);

    return max($result);
Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *

About Christina M. Gleason

Christina GleasonDeveloper who has been playing with websites since I was a preteen, it started with some tables and CSS creating a website about fairies (true story). Since then, I got a BS in Computer Science, and went to work on PHP-based websites and applications. I spent some time in custom frameworks, then a lot of time in custom WordPress development and Magento e-commerce. Industries I've worked in include logistics, healthcare, retirement communities, legal, spiritual, and HVAC.

I am an active knitter, and I also really enjoy scrapbooking and painting. Creativity has always been at my core, and I bring that into my daily workflow all the time. Lifting and working out is also important to me. I'm also married, have two daughters, and two rescue dogs Barlow and Sunshine.

Find me on: Ravelry | Instagram | Twitter | LinkedIn | GitHub