Add values to arrays in PHP
Like in other programming and scripting languages, PHP arrays are used to store data used in your application or script. The most common case is using arrays as a kind of memory for values inside a script. You can add values to different types of arrays:
- Simple array
The most simple array type is the array with only numbered index keys. This array type can hold multiple values with index numbers assigned by the developer or by PHP. You can add the array values with or without a number or index. - Associative array
This array type works almost the same as the simple array type, but in this case you have to add a string value as a key. Good examples of an associative array are the $_POST of $_GET vars created by a contact form. - Multidimensional array
This array type is so complex as you need. You can assign multiple arrays as values and/or indexes. The most common example where you face a multidimensional array, is when you parse a XML structure.
How to add values to an array with PHP?
You can add values to an array with PHP by passing single values or complete arrays. PHP has also multiple functions for array manipulations. But first I will show some examples about how I add array values with PHP code:
// the most common way just create a new array and add some values with using indexes $fruit = array('orange', 'cherry', 'lemon'); // Add more single values to the previous array $fruit[] = 'apple';
Add array values with keys to get more control
If you have a bigger array structure you need array keys if you would like to access single elements. Use numbers or strings as array keys.
// the same "$fruit" array with your own numbered keys $fruit = array(10=>'orange', 11=>'cherry', 12=>'lemon'); // add the apple on #3 $fruit[2] = 'apple'; // Note, the first array element has a zero as key // this example can be used together with a contact form $formfields = array('name'=>'Your name', 'email'=>'Your email address', 'message'=>'Your message or question'); // you can read a single value like echo $formfields['name']; // will output "Your name"
Add complete arrays as values to an array in PHP
There are many cases were a simple array with values isn’t enough and you need to use multiple array structures.
// add arrays as value to an array $records = array( array('id'=>1, 'title'=>'Google', 'url'=>'https://www.google.com'), array('id'=>2, 'title'=>'PHP', 'url'=>'http://php.net') ); // you can add single array values too $records[] = array('id'=>3, 'title'=>'finalwebsites.com', 'url'=>'https://www.finalwebsites.nl');
Add array values from your MySQL database result
There are also situations were you like to use an array to store some values from a bigger database result set. For this example we add the same kind of data like in the previous example, but than dynamically.
// create an empty array to avoid warnings $records = array(); // first create a database result and use it in the while loop // We select only thos records were the category is = "public" while ($row = $result->fetch_assoc()) { if ($row['category'] == 'public') { $records[$row['id']] = array('title'=>$row['title'], 'url'=>$row['url']); } }
Add array values with PHP functions
Sometimes it’s useful to use one the PHP functions whenever you need more control while adding array values. Here are some of them.
// areate an array by using one array for the keys and the other for its values array_combine(array('id', 'title', 'url'), array(1, 'Google', 'https://www.google.com')); // add a single array value 5 times and with a starting key = 3 $a = array_fill(3, 5, 'PHP'); // create some variable / value pairs $id = 1; $title = 'Google'; $url = 'https://www.google.com'; // put these two variable name into an array $titel_url_vars = array('title', 'url'); // create a result with values for all vars except "missing_var" because that on doesn't have a value $result = compact('id', 'missing_var', $titel_url_vars); print_r($result); // the output is like Array ( [id] => 1 [title] => Google [url] => https://www.google.com ) // is equal to array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) $number = range(0, 12); // Using the step parameter: array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) $bigger_numbers = range(0, 100, 10); // creates the 2 member fruit array $fruit = array('orange', 'cherry'); // and add two more values to the begin of the fruit array array_unshift($fruit, 'apple', 'lemon');
Using arrays in your PHP script is an essential way to solve “problems”. I’m using them very often because it’s easy and PHP can access them very fast. I hope my examples made it more clear how to add array values and how to use them in your script. Check also the array section from the PHP manual, the offer a lot of information and code examples.
If you like to check the examples in your PHP code editor, you download a .zip here.
Published in: PHP Scripts
Thanks for the nice post. I think there is a typo in:
$number = (range(0, 12);
and it should be:
$number = range(0, 12);
Vielen Dank Ralf :)
no problem :)
There is another interesting effect which maybe is worth mentioning. When you run:
http://pastebin.com/0kZG0S4N
then the result is:
10 – orange
11 – cherry
12 – lemon
2 – apple
One might expect that items with an integer index are inserted at the corresponding position, but this just does not happen in PHP. The item is always inserted at the end of the array.
Hi Ralf,
you’re right, there is no auto-sort feature, you need to run a function like
sort($fruit, SORT_NUMERIC)
after new array elements are added (that might be a good thing, sometimes)I have an array that I need to add links to, how can I add links to each country in the array below? Also, how to launch them when you select one, not by a button?
Here is the coded script:
https://pastebin.com/u179rRWG
Hi,
you need some JavaScript event to use the value from your select for a redirect to that URL.
Check this link: https://stackoverflow.com/a/12390320