PHP: Arrays

Arrays in PHP

There are three types of arrays in PHP:

  1. Indexed array
  2. Associative array
  3. Multidimensional array

Example: Simple One Dimensional, Indexed PHP Array

Array elements in this type of array are accessed through a numeric key, e.g. 0, 1, etc.


	<?php
	$artists = array("Elton John", "Eric Clapton", "Sam Cooke", "Prince");
	echo "<p>My favorite artist is " . $artists[3] . "</p>.";
	?>
	

Run it now

Output:

  My favorite artist is Prince


Example: Output One Dimensional, Indexed PHP Array with Loop


	<?php
	$artists = array("Elton John", "Eric Clapton", "Sam Cooke", "Prince");
	echo "<p>My favorite artists are: </p>";
	echo "<ul>";
	for ($x=0; $x < count($artists); $x++)
		echo "<li>" . $artists[$x];
	echo "</ul>";
	?>
	

Run it now

Output:

  My favorite artists are:   

      
  • Elton John   
  • Eric Clapton   
  • Sam Cooke   
  • Prince   

Example: Output One Dimensional, Indexed PHP Array with Loop


	$employees[0] = "Mary Smith";
	$employees[1] = "John Thomas";
	$employees[2] = "Anne Bolton";
	echo "<ul>";
	for ($x=0; $x < count($employees); $x++)
		echo "<li>" . $employees[$x];
	echo "</ul>";
	

Run it now

Output:

  • Mary Smith
  • John Thomas
  • Anne Bolton


Example: PHP Associative Array


	$employees["Mary Smith"] = "Programmer";
	$employees["John Thomas"] = "Manager";
	$employees["Anne Bolton"] = "Director";
	echo "<p>Mary Smith is a " . $employees["Mary Smith"] . ".</p>";
	

Run it now

Output:

  Mary Smith is a Programmer.