Creating Arrays
PHP gives you two ways to create arrays, but you'll mostly see the modern syntax in current code.
Old syntax vs new syntax:
The old way uses array(): $cars = array("Volvo", "BMW", "Toyota");
The modern way uses square brackets: $cars = ["Volvo", "BMW", "Toyota"];
They're identical in function, but the bracket syntax is cleaner and what you'll see in modern WordPress and MemberPress code. Use brackets.
Formatting for readability:
You can write arrays on multiple lines to make them easier to read. PHP doesn't care about whitespace or line breaks. You can even add a trailing comma after the last item — it's allowed and actually helpful when you're adding items later because you don't have to remember to add the comma.
php
$cars = [
"Volvo",
"BMW",
"Toyota",
];
How array keys work:
When you create an indexed array without specifying keys, PHP automatically assigns numbers starting from 0. So ["Volvo", "BMW", "Toyota"] is really [0 => "Volvo", 1 => "BMW", 2 => "Toyota"] under the hood. PHP just hides the numbers for convenience.
For associative arrays, you explicitly define the keys using the arrow syntax: ["brand" => "Ford", "model" => "Mustang"]. This lets you use descriptive labels instead of numbers.
Building arrays incrementally:
You don't have to create arrays all at once. You can start with an empty array and fill it piece by piece. For indexed arrays, just assign values: $cars[0] = "Volvo". For associative arrays, use key names: $car["brand"] = "Ford". This is useful when you're collecting data gradually, like building up results in a loop.
Mixing key types:
PHP technically allows you to mix numeric and string keys in the same array, though this is uncommon and can be confusing. You'll rarely need this in practice. Stick to one type per array for clarity.
Why This Matters:
Understanding array creation syntax is fundamental because you'll be reading and writing arrays constantly. Every WordPress function that returns complex data uses arrays. Every MemberPress setting, every user profile, every transaction record — all arrays. The cleaner you write them, the easier your code is to maintain.