How to Add values to arrays in PHP

By | May 28, 2017
An array is a data structure that stores one or more similar type of values in a single value.
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
  • Numeric array − If this is your first time seeing an array, then you may not quite understand the concept of an array. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. How would you go about this?
  • It wouldn’t make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done, and we show you how below.
  • Associative array −  In an associative array a key is associated with a value. If you wanted to store the salaries of your employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary
  • Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

 

 

Numeric array Example:
exampe 1:
$employee_array = array("john", "smith", "jhonson");
exampe 2:
$employee_array[0] = "john";
$employee_array[1] = "smith";
$employee_array[2] = "jhonson";

 

Associative array Example:

$income["john"] = 1000;
$income["smith"] = 2000;
$income["jhonson"] = 3000;

 

Multidimensional array Example:

$income = array(
"designer" => array (
"john" => 1000,
"smith" => 2000,
"jhonson" => 3000
),
"developer" => array (
"john" => 2000,
"smith" => 4000,
"jhonson" => 6000
)
);

Category: PHP

Leave a Reply

Your email address will not be published. Required fields are marked *