DEV Community

Antonio Sánchez
Antonio Sánchez

Posted on • Updated on • Originally published at asanchez.dev

From PHP to Go: Arrays

This is a quick and dirty article about arrays, slices, and maps in Go for all those who come from PHP and are getting started with this fantastic language.

Table of contents

  1. The Basics
  2. Arrays in Go
  3. Slices in Go
  4. Maps in Go
  5. Iterate over arrays, slices, and maps in Go
  6. Subarrays with different types

1. The basics

There are two essential things you must know:

  1. In Go, you have three kinds of similar structures to PHP arrays: arrays, slices, and maps. We will see the difference later.
  2. In Go, the elements of an array have the same type. This type must be defined when you declare the variable for this array/slice/map.

The main difference between those kinds of structures is if the length of the array is fixed or not and if they have Key/Value pairs.

Array Slice Maps
Length Fixed Variable Variable
Key/Value No No Yes

2. Arrays in Go

Let's say we want to declare an array of type string to save the days of the week:

week := [7]string{"Sunday", "Monday", "Tuesday", .., "Saturday"}
Enter fullscreen mode Exit fullscreen mode

See how there is a seven between the brackets indicating the number of elements it will contain. Once it is declared, you can't change the number of items on it, but you can change the values.

week[1] = "New Monday"  // This will work. "Monday" is now "New Monday"
week[8] = "New Day"     // This will fail, we are out of bounds.
week[1] = 1             // This will fail, cannot use type int as type string 
Enter fullscreen mode Exit fullscreen mode

Arrays as such are rarely used in Go due to their fixed length.

3. Slices in Go

Slices work like arrays as explained above, but they have variable length.

For declaring the same array as above, but as a slice, we simply omit the number between the brackets:

week := []string{"Sunday", "Monday", "Tuesday", .., "Saturday"}
Enter fullscreen mode Exit fullscreen mode

Since there is no fixed length, we can append new items to the slice:

week[8] = "New Invented Day" // This will work, since there are no bounds
weeks = append(weeks, "New Invented Day") // We can also use the method append()
Enter fullscreen mode Exit fullscreen mode

And we can also delete items from the slice. If we want to remove the item of index 1 ("New Monday"):

weeks = append(week[:1], week[2:]...)
Enter fullscreen mode Exit fullscreen mode

Note that, as in the code above, we can get some items of any slice (and arrays) using the brackets after the variable :

week[4:6] // This will return ["Friday", "Saturday"]
Enter fullscreen mode Exit fullscreen mode

To know the number of elements in any slice, use the function len()

numberOfDays := len(week)
Enter fullscreen mode Exit fullscreen mode

4. Maps in Go

If you need to use key/value pairs, then you need to use maps.

For instance, if you need to replicate this PHP array in Go:

<?php 
    $products = [
    "Cap" => "Red", 
    "T-Shirt" => "Blue"
    ]; 
?>
Enter fullscreen mode Exit fullscreen mode

You would need to define a map of key type string and value type string. You can use one of those ways:

products := make(map[string]string) 
products := map[string]string{}
products := map[string]string{ 
    "Cap":     "Red", 
    "T-Shirt": "Red",
}
Enter fullscreen mode Exit fullscreen mode

Since now we have key/value pairs, you can append elements without using append:

products["Pants"] = "Blue"
Enter fullscreen mode Exit fullscreen mode

5. Iterate over arrays, slices, and maps in Go

The most common way is to use range

for key,value := range products {
    fmt.Printf("Key: %s Value: %s\n", key, value)
}
Enter fullscreen mode Exit fullscreen mode

6. Subarrays with different types

What if I need an array of arrays, also with variables of different type, like I can do on PHP?

You can create "maps of maps". For instance, let's say you need to have this PHP array in Go:

<?php 
    $products = [
    "Cap" => [
        "Color" => "Red",
        "Size" => "XL"
    ],
    "T-Shirt" => [
            "Color" => "Blue",
            "Size" => "XS"
        ]
    ];
?>
Enter fullscreen mode Exit fullscreen mode

You could create such a map doing this:

products := make(map[string]map[string]string)
Enter fullscreen mode Exit fullscreen mode

If you need to have different variables of different type in your subarrays, you need to define new variable types using structs:

type Property struct {
  Color string
  Size string
  Price int
}

products := make(map[string]Property)

products["Cap"] = Property{
        Color: "Red",
        Size: "XL", 
        Price: 30,
}
Enter fullscreen mode Exit fullscreen mode

That's all Folks! ;)

Discussion (4)

Collapse
asanchez profile image
Antonio Sánchez Author • Edited on

Titles 4, 5 and 6 are not being represented as titles. This must be a problem of dev.to, since the markdown is correct. I am sorry for the inconveniences and I hope someone from dev.to take a look at this.

Collapse
asanchez profile image
Antonio Sánchez Author • Edited on

Fixed. I hade to make sure the closing </pre> tag was in another line as the opening <pre> tag. I don't know why, but it is working like this.

Collapse
andy profile image
Andy Zhao (he/him)

Hey Antonio, we recommend using codeblocks like you would with Markdown in order to get the <pre> tag functionality. Here's an example:

Code block usage example

Including the language php after the first set of triple backticks will add syntax highlighting.

Hope that helps!

Thread Thread
asanchez profile image
Antonio Sánchez Author

Hi Andy, thanks a lot! I am not so experienced working with markdown. I will edit the post right now to do this.