You can create an array using the array()
function or not.
First let me show you how to create with the array()
function:
<?php
$fruits = array ('Apple', 'Pear', 'Banana', 'Cherry');
?>
We have assigned 4 values to the array of $fruits
with the array()
function.
Let’s do the same without using a function:
<?php
$fruits[0] = 'Apple';
$fruits[1] = 'Pear';
$fruits[2] = 'Banana';
$fruits[3] = 'Cherry';
?>
In the non-functional method, how the array actually results is revealed.
The array()
function above and the arrays we created without the function did the same.
In this array that we create with the array()
function, the key of each value is numeric, so the keys go as 0, 1, 2, 3,… . The value of key 0 of the $fruits
array above is Apple and the value of key 1 is Pear.
Use the array()
function to create arrays whose keys are non-numeric and will be as you wish:
<?php
$fruits = array ('one' => 'apple', 'two' => 'pear', 'three' => 'banana');
?>
I’ve mentioned my keys here myself. Let me do the same without using the array function:
<?php
$fruits['one'] = 'Apple';
$fruits['two'] = 'Pear';
$fruits['three'] = 'Banana';
?>
This is the function of the previous example.
You need one key in the arrays and then a value for each key. Here is the key part and the part that is the value.
<?php
$array['key'] = 'value';
?>
You can enter numbers or text in the key section. Array key numbers are ideal for sequences. You can work with arrays more easily.