In php there are a few methods to add items to an array. The most efficient way being using php’s built in operators. For the c++ people who have implemented operator overloading before you will understand exactly what this is. Operators being +-.[] etc. which it assigned to a specific type of class, object or variable type. In php we make use of such an operator to append items to an array. The operator in question being the [] operator.
Example of how to add items to an array
In the below piece of code which will simply just add some strings to an array.
<?php
$ourarray = array(); //Make sure our array is blank initially
$ourarray[] = “hello”;
$ourarray[] = “world”;
?>
If you run print_r on this array you should see your two words, hello and world. Let’s look at adding items to arrays which already have indexes. For this example we will use an array which has the key “names”.
<?php
$ourarray[‘names’][] = “John”;
$ourarray[‘names’][] = “Mary”;
print_r($ourarray);
?>
You can also append whole arrays for example.
<?php
$ourarray[‘names’][] = array(‘John’,’Mary’);
print_r($ourarray);
?>
What else can we add to arrays
Arrays are quite versatile in php, you can add many different types of objects, variable type and arrays to your arrays. The other big benefit is that php ships with the json_encode function which makes arrays quite easy to turn into json. This can help with many things, well one for your rest apis. Other than that it will allow you to be able to take snapshots of your data for later loading. You could potentially save your arrays as json strings in a database then later retrieve them to restore the state of your application for a specific user. Just giving that extra bit of user experience flexibility in your applications.
Next steps, what else should you learn
Php has a number of functions which relate to arrays some of the common ones you might want to learn is the following when doing array manipulation.
array_merge
unset
array_sum
array_copy
array_chunk
array_keys
array_diff
These will help you remove, add, merge arrays, break arrays up into different arrays, give you the indexes between arrays and also show you any differences between two arrays as well.
Conclusion
Php arrays are very useful in structuring your data into a nicely indexed memory array. Arrays are fast to access. Find ways to incorporate them efficiently into your applications.
Report



