What is an example of an associative array in php?

In this tutorial you'll learn how to store multiple values in a single variable in PHP.

What is PHP Arrays

Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. Let's suppose you want to store colors in your PHP script. Storing the colors one by one in a variable could look something like this:

But what, if you want to store the states or city names of a country in variables and this time this not just three may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable. And here array comes into play.


Types of Arrays in PHP

There are three types of arrays that you can create. These are:

  • Indexed array — An array with a numeric key.
  • Associative array — An array where each key has its own specific value.
  • Multidimensional array — An array containing one or more arrays within itself.

Indexed Arrays

An indexed or numeric array stores each array element with a numeric index. The following examples shows two ways of creating an indexed array, the easiest way is:

Note: In an indexed or numeric array, the indexes are automatically assigned and start with 0, and the values can be any data type.

This is equivalent to the following example, in which indexes are assigned manually:


Associative Arrays

In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the following example the array uses keys instead of index numbers:

22, "Clark"=>32, "John"=>28);
?>

The following example is equivalent to the previous example, but shows a different way of creating associative arrays:


Multidimensional Arrays

The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain array within itself and so on. An example of a multidimensional array will look something like this:

 "Peter Parker",
        "email" => "",
    ),
    array(
        "name" => "Clark Kent",
        "email" => "",
    ),
    array(
        "name" => "Harry Potter",
        "email" => "",
    )
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>


Viewing Array Structure and Values

You can see the structure and values of any array by using one of two statements — var_dump() or print_r(). The print_r() statement, however, gives somewhat less information. Consider the following example:

The print_r() statement gives the following output:

Array ( [0] => London [1] => Paris [2] => New York )

This output shows the key and the value for each element in the array. To get more information, use the following statement:

This var_dump() statement gives the following output:

array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }

This output shows the data type of each element, such as a string of 6 characters, in addition to the key and value. In the next chapter you will learn how to sort array elements.

You will learn how to loop through the values of an array in the later chapter.

What is a PHP Array?

A PHP array is a variable that stores more than one piece of related data in a single variable.

Think of an array as a box of chocolates with slots inside.

The box represents the array itself while the spaces containing chocolates represent the values stored in the arrays.

The diagram below illustrates the above syntax.

In this tutorial, you will learn-

  • Numeric Arrays
  • PHP Associative Array
  • PHP Multi-dimensional arrays
  • PHP Array operators

Numeric Arrays

Numeric arrays use number as access keys.

An access key is a reference to a memory slot in an array variable.

The access key is used whenever we want to read or assign a new value an array element.

Below is the syntax for creating numeric array in php.

Array Example

Or

 value, …);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let’s now look at an example of a numeric array.

Suppose we have 5 movies that we want to store in array variables.

We can use the example shown below to do that.

Here,

What is an example of an associative array in php?

Each movie is given an index number that is used to retrieve or modify its value. Observe the following code-

Output:

Once upon a time in China Eastern Condors

As you can see from the above examples, working with arrays in PHP when dealing with multiple values of the same nature is very easy and flexible.

Alternatively, the above array variables can also be created using the following code.

 "Shaolin Monk",
               1 => "Drunken Master",
               2 => "American Ninja",
               3 => "Once upon a time in China",
               4 =>"Replacement Killers" );
echo $movie[4];
?>

Output:

Replacement Killers

Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.

Below is the syntax for creating associative array in php.

 value);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[‘key_name’]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let’s suppose that we have a group of persons, and we want to assign the gender of each person against their names.

We can use an associative array to do that.The code below helps us to do that.

 "Female", "John" => "Male", "Mirriam" => "Female");
print_r($persons); 
echo ""; 
echo "Mary is a " . $persons["Mary"];
?>

HERE,

What is an example of an associative array in php?

Output:

Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

Associative array are also very useful when retrieving data from the database.

The field names are used as id keys.

PHP Multi-dimensional arrays

These are arrays that contain other nested arrays.

The advantage of multidimensional arrays is that they allow us to group related data together.

Let’s now look at a practical example that implements a php multidimensional array.

The table below shows a list of movies by category.

Movie title Category
Pink Panther Comedy
John English Comedy
Die Hard Action
Expendables Action
The Lord of the rings Epic
Romeo and Juliet Romance
See no evil hear no evil Comedy

The above information can be represented as a multidimensional array. The code below shows the implementation.

 array("Pink Panther", "John English", "See no evil hear no evil"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"Romance" => array("Romeo and Juliet")
);
print_r($movies);
?>

HERE,

What is an example of an associative array in php?

Output:

Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => See no evil hear no evil ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array ( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

Another way to define the same array is as follows

 array(

                                0 => "Pink Panther",

                                1 => "john English",

                                2 => "See no evil hear no evil"

                                ),

                "action" => array (

                                0 => "Die Hard",

                                1 => "Expendables"

                                ),

                "epic" => array (

                                0 => "The Lord of the rings"

                                ),

                "Romance" => array

                                (

                                0 => "Romeo and Juliet"

                                )

);
echo $film["comedy"][0];
?>

Output:

Pink Panther

Note: the movies numeric array has been nested inside the categories associative array

PHP Arrays: Operators

Operator Name Description How to do it Output
x + y Union Combines elements from both arrays
 1);

$y = array('value' => 10);

$z = $x + $y;
?>
Array([id] => 1 [value] => 10)
X == y Equal Compares two arrays if they are equal and returns true if yes.
 1);

$y = array("id" => "1");

if($x == $y)
{
echo "true";
}
else
{
echo "false";

}
?>
True or 1
X === y Identical Compares both the values and data types
 1);

$y = array("id" => "1");

if($x === $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
X != y, x <> y Not equal
 1);

$y = array("id" => "1");

if($x != $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
X !== y Non identical
 1);

$y = array("id" => "1");

if($x !== $y)
{
echo "true";
}
else
{
echo "false";
}
?>
True or 1

PHP Array Functions

Count function

The count function is used to count the number of elements that an php array contains. The code below shows the implementation.

Output:

3

is_array function

The is_array function is used to determine if a variable is an array or not. Let’s now look at an example that implements the is_array functions.

Output:

1

Sort

This function is used to sort arrays by the values.

If the values are alphanumeric, it sorts them in alphabetical order.

If the values are numeric, it sorts them in ascending order.

It removes the existing access keys and add new numeric keys.

The output of this function is a numeric array

 "Female", "John" => "Male", "Mirriam" => "Female");

sort($persons);

print_r($persons);
?>

Output:

Array ( [0] => Female [1] => Female [2] => Male )

ksort

This function is used to sort the array using the key. The following example illustrates its usage.

 "Female", "John" => "Male", "Mirriam" => "Female");

ksort($persons);

print_r($persons);
?>

Output:

Array ( [John] => Male [Mary] => Female [Mirriam] => Female )

asort

This function is used to sort the array using the values. The following example illustrates its usage.

 "Female", "John" => "Male", "Mirriam" => "Female");

asort($persons);

print_r($persons);

?>

Output:

Array ( [Mary] => Female [Mirriam] => Female [John] => Male )

Why use arrays?

  • Contents of Arrays can be stretched,
  • Arrays easily help group related information such as server login details together
  • Arrays help write cleaner code.

Summary

  • Arrays are special variables with the capacity to store multi values.
  • Arrays are flexibility and can be easily stretched to accommodate more values
  • Numeric arrays use numbers for the array keys
  • PHP Associative array use descriptive names for array keys
  • Multidimensional arrays contain other arrays inside them.
  • The count function is used to get the number of items that have been stored in an array
  • The is_array function is used to determine whether a variable is a valid array or not.
  • Other array functions include sort, ksort, assort etc.

Which is a example of associative array *?

Example. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000"); echo "Sonoo salary: ".

What are the types of array in PHP with example?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

Are all arrays in PHP associative?

PHP treats all arrays as associative, so there aren't any built in functions.

Is $_ POST an associative array?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.