Introduction
Our publishing command needs to handle more than one article. We want an ordered list of articles to review, and we want to look up each article's word count by its slug.
In PHP, we could reach for an array for both jobs. A PHP array is an ordered map, so the same type supports a list of values and values stored under named keys. The PHP array documentation describes that flexibility.
Go separates those choices. An array has a fixed length, a slice gives us a sequence whose length can change, and a map associates keys with values. Choosing between them affects more than syntax. It determines whether order is meaningful, how we add values, and whether two variables can change the same stored elements.
This is Part 3 of Go for PHP Developers. In Part 2, we distinguished an unknown word count from a count of zero. Let's keep that distinction while building a report for several articles, without introducing an article struct or a storage layer yet.
Set Up a Place to Experiment
These examples use Go 1.27.4, the latest stable release listed in the
official downloads feed when checked on December 3, 2026.
Only the standard library is needed. Check go version before starting, or follow
the installation instructions.
Create a fresh directory for this part:
mkdir publishing-collections
cd publishing-collections
go mod init example.com/publishing
Create main.go with this starting program:
package main
import "fmt"
func main() {
fmt.Println("Preparing the article list")
}
Run go run . to see the message. Until we assemble the report, each short Go block
below replaces the body of main. Keep package main and the fmt import.
Arrays Have a Length in Their Type
An array holds a fixed number of elements of one type. Here's a pair of labels that our publishing command could use:
labels := [2]string{"Draft", "Published"}
copied := labels
copied[0] = "Needs review"
fmt.Println(len(labels))
fmt.Println(labels[0])
fmt.Println(copied[0])
The output is:
2
Draft
Needs review
The type is [2]string. Its length, 2, is part of the type, and its elements are
strings. [3]string is a different type, so we can't assign this array directly to
a variable of that type. The array type rules
make that distinction explicit.
Assignment copies the array's elements. In this example, changing copied[0] leaves
labels[0] alone. Remember that result when we get to slices.
The brackets also provide indexed access. The first element is at index 0, and
the last is at len(labels)-1. A runtime index outside that range causes a panic.
I would choose an array when the fixed length is part of the data's meaning. Our article list can grow, so a slice is a better fit for that list.
Use a Slice for a List That Can Grow
The missing length inside the brackets changes the type:
titles := []string{"Learning Go", "Types and Nil"}
titles = append(titles, "Beyond the PHP Array")
for index, title := range titles {
fmt.Printf("%d: %s\n", index+1, title)
}
The output is:
1: Learning Go
2: Types and Nil
3: Beyond the PHP Array
[]string is a slice of strings. append returns a slice that includes the new
element, so we assign that result back to titles. We'll look at why it returns
a value rather than changing the variable for us in a moment.
range supplies each index and element in increasing index order for a slice.
index+1 changes how we number the displayed list, while the actual indexes still
start at zero. If we only need the value, write for _, title := range titles.
The blank identifier _ discards the index.
Each iteration's title is a copy of the element value. Reassigning that local
string doesn't replace the element in titles. To change a stored element, assign
through its index, such as titles[index] = "Updated title".
For this report, I want the slice to keep the reader's chosen order. We shouldn't have to recover that order from a collection designed for lookup.
Length and Capacity Answer Different Questions
A slice gives access to part of an underlying array. The slice value describes where that part starts, its current length, and its capacity.
The length, returned by len, is the number of elements currently in the slice.
The capacity, returned by cap, is the number of elements available from its
starting position to the end of the underlying array.
Let's allocate room for four titles without adding any titles yet:
titles := make([]string, 0, 4)
fmt.Printf("len=%d cap=%d\n", len(titles), cap(titles))
titles = append(titles, "Learning Go")
fmt.Printf("len=%d cap=%d\n", len(titles), cap(titles))
The output is:
len=0 cap=4
len=1 cap=4
The arguments to make specify the type, length, and capacity. If we wrote
make([]string, 4), we'd get four existing empty strings, with both length and
capacity equal to four. Appending a title would then put it after those empty strings.
Use a zero length when you want to collect values with append.
Capacity doesn't make an index valid. Before the first append above, titles[0]
would panic because the length is still zero, even though space for four elements
has been allocated.
When the existing capacity is enough, append reuses the underlying array. When
it isn't enough, append allocates another array and copies the existing elements
into it. The returned slice describes the result in either case. Don't rely on a
particular capacity growth factor. The
append specification
guarantees enough room, without prescribing a doubling rule.
Preallocating capacity is optional. I would only set it when the expected size is
already known. We can also leave capacity to append, as the final report does.
A Second Slice Can Share the Same Elements
Slicing an existing slice doesn't copy its elements:
titles := []string{"Learning Go", "Types and Nil", "Beyond the PHP Array"}
preview := titles[:2]
fmt.Printf("titles: len=%d cap=%d\n", len(titles), cap(titles))
fmt.Printf("preview: len=%d cap=%d\n", len(preview), cap(preview))
preview[0] = "Go Basics"
preview = append(preview, "Slice Storage")
fmt.Printf("%q\n", titles)
The output is:
titles: len=3 cap=3
preview: len=2 cap=3
["Go Basics" "Types and Nil" "Slice Storage"]
titles[:2] starts at index zero and stops before index two. It creates a slice
with length two that still has access to the same underlying array, including its
third slot through capacity. Before either change, the relationship is:
titles len=3 cap=3 ---+
+--> [Learning Go][Types and Nil][Beyond the PHP Array]
preview len=2 cap=3 ---+ <--- preview's elements ---><-- spare capacity -->
Changing preview[0] changes the first shared element. Then the append reuses the
third slot because preview still has room for it. That slot is already part of
titles, so its previous third title is replaced too.
The two slices have separate lengths, but share element storage. If we wrote
preview := titles instead, we'd copy the slice value with the same length and
capacity, while still sharing the elements. This differs from our array assignment.
When a separate editable list is needed, allocate another slice and copy into it:
titles := []string{"Learning Go", "Types and Nil"}
preview := make([]string, len(titles))
copied := copy(preview, titles)
preview[0] = "Go Basics"
fmt.Println(copied)
fmt.Println(titles[0])
fmt.Println(preview[0])
It prints 2, then Learning Go, then Go Basics. copy returns the number of
elements copied, limited by the shorter length of its source and destination.
Allocating make([]string, 0, len(titles)) here would copy zero elements because
the destination's length would be zero.
Our elements are strings, so replacing one string in the copied list leaves the other list alone. Copying elements isn't a recursive copy of any data those elements might themselves reference. We'll return to that distinction when we discuss values and pointers in Part 4. The official slice explanation provides more diagrams of this storage.
Nil Slices Can Be Appended To
The zero value from Part 2 is useful when collecting an unknown number of items:
var titles []string
fmt.Println(titles == nil, len(titles), cap(titles))
titles = append(titles, "Learning Go")
fmt.Println(titles == nil, len(titles))
empty := []string{}
fmt.Println(empty == nil, len(empty))
The output is:
true 0 0
false 1
false 0
A nil slice has length and capacity zero. We can range over it, read its length,
or append to it without initialising it with make first. The empty literal in
the last part is non-nil, even though its length is also zero.
If all our function needs to know is whether there are any titles, len(titles) == 0
handles both empty and nil slices. Use a nil check only when the distinction matters
to the function's contract. Neither form gives us an element at index zero.
Use a Map for Lookup by Slug
We have a list for order. Now we need a count for a particular article:
wordCounts := map[string]int{
"learning-go": 1200,
"empty-draft": 0,
}
count, counted := wordCounts["empty-draft"]
fmt.Println(count, counted)
count, counted = wordCounts["next-article"]
fmt.Println(count, counted)
The output is:
0 true
0 false
map[string]int declares string keys and integer values. Every key in this map
has the same type, and every value has the same type. A slice couldn't be a map
key because map keys must support equality comparisons, while strings are a valid choice.
The lookup can return two values. The first is the stored integer, or its zero
value when the key is absent. The second tells us whether an entry actually exists.
You'll often see that boolean named ok. I used counted to make its meaning clear here.
This is the distinction we needed in Part 2. A zero value alone doesn't tell us whether the word count is known. The map's presence result does.
If you normally reach for PHP's isset, remember that it returns false for a
present key whose value is null. PHP's
array_key_exists
checks key presence independently of the value. Our map[string]int cannot store
nil as an integer, but checking presence separately remains the useful comparison.
Initialise a Map Before Writing to It
A nil map supports lookup, but adding an entry requires initialisation:
var wordCounts map[string]int
count, counted := wordCounts["learning-go"]
fmt.Println(count, counted, len(wordCounts))
wordCounts = make(map[string]int)
wordCounts["learning-go"] = 1200
fmt.Println(wordCounts["learning-go"], len(wordCounts))
delete(wordCounts, "learning-go")
fmt.Println(len(wordCounts))
The output is 0 false 0, then 1200 1, then 0.
Try moving wordCounts["learning-go"] = 1200 before the make call. That deliberate
change causes a runtime panic because the map is still nil. Restore the original order
before continuing. Unlike append on a nil slice, assignment into a nil map doesn't
create the storage for us.
A map literal, such as the one in the previous example, also creates a writable map.
delete removes a key. Deleting a missing key, including from a nil map, does nothing.
The map specification describes these operations.
Assigning a map to another variable shares the same map. It doesn't make an independent copy of its entries. If we later need a second editable map, we must copy those entries into a new one.
Map Iteration Doesn't Define Display Order
PHP arrays preserve insertion order. Go maps don't offer that guarantee:
wordCounts := map[string]int{
"learning-go": 1200,
"empty-draft": 0,
}
for slug, count := range wordCounts {
fmt.Printf("%s: %d\n", slug, count)
}
Both entries are printed, but either can come first. The order isn't specified and isn't guaranteed to stay the same between iterations. Seeing the same order during a few local runs doesn't establish a guarantee.
If we wanted alphabetical output, we could collect and sort the keys. For our publishing report, the reader supplies a review order, so I would keep that order in a slice and use the map only to retrieve counts. The range rules explain the iteration guarantees for each type.
Build the Report With a Slice and a Map
Let's put both collections to work. A slice of slugs defines the report's order, and a map stores the counts that are currently known. This replaces our single-article message exercise with a report function in the same small publishing application.
Create report.go:
package main
import "fmt"
func publicationMessages(slugs []string, wordCounts map[string]int) []string {
var messages []string
for _, slug := range slugs {
count, counted := wordCounts[slug]
if !counted {
messages = append(messages, "Word count unknown: "+slug)
continue
}
if count <= 0 {
messages = append(messages, "Draft needs content: "+slug)
continue
}
message := fmt.Sprintf("Ready to publish: %s (%d words)", slug, count)
messages = append(messages, message)
}
return messages
}
The loop visits the slugs in their supplied order. continue skips the remainder
of the current iteration after adding an unknown-count or empty-draft message.
Missing entries and zero counts follow different branches, and negative counts also
fail our content rule. With no slugs, the function returns its initial nil slice.
Replace the complete main.go with:
package main
import "fmt"
func main() {
slugs := []string{"learning-go", "empty-draft", "next-article"}
wordCounts := map[string]int{
"empty-draft": 0,
"learning-go": 1200,
}
for _, message := range publicationMessages(slugs, wordCounts) {
fmt.Println(message)
}
}
Run go run .. The output is:
Ready to publish: learning-go (1200 words)
Draft needs content: empty-draft
Word count unknown: next-article
The report uses slugs as identifiers, so it prints those rather than article titles. It assumes the caller supplies suitable slugs and counts. We aren't calculating word counts, checking publication dates, or persisting articles yet. Counts for slugs outside the requested list are ignored, and repeated slugs would produce repeated messages.
Test Order and Missing Values
Create report_test.go:
package main
import "testing"
func TestPublicationMessagesKeepsOrderAndDistinguishesMissingCounts(t *testing.T) {
slugs := []string{"next-article", "empty-draft", "learning-go"}
wordCounts := map[string]int{
"learning-go": 1200,
"empty-draft": 0,
}
want := []string{
"Word count unknown: next-article",
"Draft needs content: empty-draft",
"Ready to publish: learning-go (1200 words)",
}
got := publicationMessages(slugs, wordCounts)
if len(got) != len(want) {
t.Fatalf("got %d messages, want %d", len(got), len(want))
}
for index, message := range got {
if message != want[index] {
t.Fatalf("message %d = %q, want %q", index, message, want[index])
}
}
}
func TestPublicationMessagesWithNilCounts(t *testing.T) {
got := publicationMessages([]string{"learning-go"}, nil)
want := "Word count unknown: learning-go"
if len(got) != 1 {
t.Fatalf("got %d messages, want 1", len(got))
}
if got[0] != want {
t.Fatalf("message = %q, want %q", got[0], want)
}
}
func TestPublicationMessagesWithoutSlugs(t *testing.T) {
got := publicationMessages(nil, nil)
if len(got) != 0 {
t.Fatalf("got %d messages, want none", len(got))
}
}
The first test uses an order that differs from the map literal and expects different messages for an absent count and a stored zero. Replacing the two-value lookup with an assumption that zero means missing would make that test fail. The other tests check reading a nil map and processing an empty list.
Run the checks and build the executable:
go fmt ./...
go test ./...
go vet ./...
go build -o publisher .
./publisher
The tests report ok for example.com/publishing. The executable prints the same
three lines as go run .. These checks cover message selection and order for the
tested inputs, rather than whether the counts match any real article content.
Where the PHP Comparison Stops
For an ordered list, I would start with a slice. For lookup by a unique key, I would start with a map. An array fits when the length is part of the value's type. Those choices make responsibilities visible without trying to recreate every use of a PHP array through one Go type.
The assignment behaviour also needs its own explanation. PHP array assignment has value semantics unless references are involved. A Go array assignment copies its elements, while assigning a slice or map can leave two variables sharing stored data. Don't assume the behaviour of one collection applies to the others.
Our slice of slugs and map of counts are enough for this report. If an article later needs its title and publication state kept together, we'll introduce a struct for that data. There is no need to turn this exercise into a map of unrelated field types.
Conclusion
Try changing slugs to put the unknown article first, then add its count to the map
and rerun the report. The output order should still follow the slice, while the message
for that article changes because its count is now present.
Then revisit the preview example. Change an element through the shared slice, and compare that with allocating and copying into a separate slice. Being able to predict which titles change is more useful than memorising the bracket syntax alone.
Next in Go for PHP Developers: Values, Pointers, and Mutation. We'll follow what functions receive and what they can change, using PHP object assignment and references as comparison points.
I hope that you liked this article and if you do, don't forget to share this article with your friends!!! See ya!