PHP Create Arrays
Posted 2024-05-17 08:01:55
0
3K
Create Array
You can create arrays by using the array()
function:
You can also use a shorter syntax by using the []
brackets:
Multiple Lines
Line breaks are not important, so an array declaration can span multiple lines:
Trailing Comma
A comma after the last item is allowed:
Array Keys
When creating indexed arrays the keys are given automatically, starting at 0 and increased by 1 for each item, so the array above could also be created with keys:
As you can see, indexed arrays are the same as associative arrays, but associative arrays have names instead of numbers:
Declare Empty Array
You can declare an empty array first, and add items to it later:
The same goes for associative arrays, you can declare the array first, and then add items to it:
Example
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
Try it Yourself »Mixing Array Keys
You can have arrays with both indexed and named keys:
Example
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
Try it Yourself »Căutare
Categorii
- Art
- Causes
- Crafts
- Dance
- Drinks
- Film
- Fitness
- Food
- Jocuri
- Gardening
- Health
- Home
- Literature
- Music
- Networking
- Alte
- Party
- Religion
- Shopping
- Sports
- Theater
- Wellness
Citeste mai mult
PHP Numbers
In this chapter we will look in depth into Integers, Floats, and Number Strings.
PHP Numbers...
PHP Continue
The continue statement can be used to jump out of the current iteration of a loop, and...
PHP Variables Scope
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a...
PHP Data Types
PHP Data Types
Variables can store data of different types, and different data types can do...
PHP foreach Loop
The foreach loop - Loops through a block of code for each element in an array or each...