Go compared with php. Arrays and slices

Creating

Create an array in PHP

$myStringArray = ["One","Two","Three"];
                

In Go creating the above is a little more verbose and like variable assignment above there's also multiple ways to create a slice. The most similar way to that of PHP is as follows.

myStringArray := []string{"One","Two","Three"}
                

Appending

Things become a little trickier when you want to append to an array. In PHP world this is easy

$myStringArray=["One", "Two", "Three"];\n
$myStringArray[] = "Four";
                

In Go you need to use the global append function

myStringArray := []string{"One","Two","Three"}
myStringArray = append(myStringArray,"Four")
fmt.Println(myStringArray)
                    

Extracting

PHPs vast suite of inbuilt array functions make working with arrays simple. For instance to extract part of an array in PHP you can use the array_slice function.

$myArray = ["a","b","c","d","e"];
$myNewArray = array_slice($myArray,2,2); // ["c","d"]
                

To achieve the same functionality in Go a little piece of syntactical magic is required

myArray := []string{"a", "b", "c", "d", "e"}
myNewArray := append([]string{},myArray[2:4]...) // ["c","d"]
                    

Iterating

Iterating over a range of any function in PHP can be done using the construct.

$myStringArray = ["One","Two","Three"]
foreach ($myStringArray as $key => value) {
  echo $key." ".$string."\r\n";
}
//0 One
//1 Two
//3 Three
                

In Go we use the range construct

myStringArray := []string{"one","two","three"}
for key,value := range myStringArray {
  fmt.Println(key, value)
}

Imploding and Exploding

Joining an array into a string in PHP can be done using the built in implode function

$myStringArray = ["One","Two","Three"];
$myString = implode(" ",$myStringArray);
echo $myString; // One Two Three
                

Golang uses the join function from the strings package which you are required to import to use

package main

import (
  "fmt"
  "strings"
)

func main() {
  myStringArray := []string{"one","two","three"}
  fmt.Println(strings.Join(myStringArray, " "))
}
                
To take a string and turn it into an array in PHP we use the explode function
$myString = "One Two Three";
$myStringArray = explode(" ",$myString); // ["One", "Two", "Three"]
                

To take a string and turn it into an array in Golang we again need to use the strings package, but this time use the split function

myString := "one two three"
myStringArray := strings.Split(myString, " ")
fmt.Println(myStringArray)