From PHP to Go: Arrays
Tags: php, go
Published: 2019-03-02 15:17:47

---
title: "From PHP to Go: Arrays"
published: true
description: "Quick and dirty article about arrays, slices and maps in Go for all those who come from PHP"
series: "From PHP to Go: a quick and dirty guide"
canonical_url: https://asanchez.dev/blog/from-php-to-go-arrays/
tags: 
    - PHP
    - Go
---
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](#basics)
2. [Arrays in Go](#arrays)
3. [Slices in Go](#slices)
4. [Maps in Go](#maps)
5. [Iterate over arrays, slices, and maps in Go](#iterate)
5. [Subarrays with different types](#different)



<a name="basics"></a>
## 1. The basics 
There are two essential things you must know:  

1. In Go, you have three kinds of similar structures to PHP arrays: <a href="https://gobyexample.com/arrays" target="_blank">arrays</a>, <a href="https://gobyexample.com/slices" target="_blank">slices</a>, and <a href="https://gobyexample.com/maps" target="_blank">maps</a>. We will see the difference later. 
2. In Go, the elements of an array have the same <a href="https://tour.golang.org/basics/11" target="_blank">type</a>. 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      |

<a name="arrays"></a>
## 2. Arrays in Go
Let's say we want to declare an array of type string to save the days of the week:

```go
week := [7]string{"Sunday", "Monday", "Tuesday", .., "Saturday"}
```

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. 

```go
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 
```

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

<a name="slices"></a>
## 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: 

```go
week := []string{"Sunday", "Monday", "Tuesday", .., "Saturday"}
```

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

```go
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()
```

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

```go
weeks = append(week[:1], week[2:]...)
```

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

```go
week[4:6] // This will return ["Friday", "Saturday"]
```

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

```go
numberOfDays := len(week)
```
    
<a name="maps"></a>

## 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
<?php 
    $products = [
	"Cap" => "Red", 
	"T-Shirt" => "Blue"
    ]; 
?>
```

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

```go
products := make(map[string]string) 
products := map[string]string{}
products := map[string]string{ 
	"Cap":     "Red", 
	"T-Shirt": "Red",
}
```

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

```go
products["Pants"] = "Blue"
```

<a name="iterate"></a>
    
## 5. Iterate over arrays, slices, and maps in Go

The most common way is to use `range`

```go
for key,value := range products {
	fmt.Printf("Key: %s Value: %s\n", key, value)
}
```

<a name="different"></a>
## 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
<?php 
    $products = [
	"Cap" => [
		"Color" => "Red",
		"Size" => "XL"
	],
	"T-Shirt" => [
            "Color" => "Blue",
            "Size" => "XS"
        ]
    ];
?>
```

You could create such a map doing this:

```go
products := make(map[string]map[string]string)
```

If you need to have different variables of different type in your subarrays, you need to define new variable types using <a href="https://gobyexample.com/structs" target="_blank">structs</a>:

```go
type Property struct {
  Color string
  Size string
  Price int
}

products := make(map[string]Property)

products["Cap"] = Property{
        Color: "Red",
        Size: "XL", 
        Price: 30,
}
```

That's all Folks! ;)