PHP Arrays

There are some kind of arrays:

  • Numeric array – An array with a numeric ID key
  • Associative array – An array where each ID key is associated with a value

Numeric Arrays

A numeric array stores each element with a numeric ID key.

There are different ways to create a numeric array.

Example 1

In this example the ID key is automatically assigned:

$first_name = array(“Peter”,”John”,”Tony”);

Example 2

In this example we assign the ID key manually:

$first_name[0] = “Peter”;
$first_name[1] = “John”;
$first_name[2] = “Tony”;

Example that used in Php

<?php
$first_name[0] = “Peter”;
$first_name[1] = “John”;
$first_name[2] = “Tony”;

echo “$first_name[1] and $first_name[2] are $first_name[0]‘s friends”;
?>

And the output is

John and Tony are Peter’s friends

Associative Arrays

An associative array, each ID key is associated with a value.

When storing data about specific named values, a numerical array is not always the best way to do it.

With associative arrays we can use the values as keys and assign values to them.

Example 1

In this example we use an array to assign ages to the different persons:

$ages = array(“Peter”=>32, “John”=>30, “Tony”=>34);

Example 2

This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = “32″;

$ages['John'] = “30″;

$ages['Tony'] = “34″;

Example used in PHP :

<?php

$ages['Peter'] = “32″;

$ages['John'] = “30″;

$ages['Tony'] = “34″;

echo “Peter is ” . $ages['Peter'] . ” years old.”;

?>

and output is

Peter is 32 years old.

Leave a comment

5 Comments.

  1. Nice write up¡­usually I never reply to these thing but this time I will,Thanks for the great info

  2. I wanted to thank you for this great read!! I definitely enjoying every little bit of it.I have you bookmarked to check out new stuff you post.

  3. thank you

  4. Thx I found just the info I already searched across the whole internet and just couldn’t find. What a perfect website.

  5. hilarious AND you brought out the world’s first lol cat grammarnazis

Leave a Reply


[ Ctrl + Enter ]