PHP Arrays Example

Definition of Array (computing):

An array is like a container having sections for holding data and each section has a unique identity called index which is used to access an element in that section.

Types of Arrays in PHP:

Indexed arrays: Arrays having numeric indexes.
Associative arrays: Arrays having named keys.
Multidimensional arrays: Arrays with in arrays.

PHP Indexed Array Syntax:


<?php
$php_indexed_array = array("PHP","INDEXED","ARRAY");

//Iterate through an array declared above

for($index = 0; $index < count($php_indexed_array); $index++)
{
echo $index ." => ". $php_indexed_array[$index] ."<br/ >" ;
}
?>

/*** OUTPUT ***/

0 => PHP
1 => INDEXED
2 => ARRAY

PHP Associative Array Syntax:


<?php
$php_assoc_array = array("lang"=>"PHP", "c_type"=>"ASSOCIATIVE", "p_type"=>"ARRAY");

//Iterate through an array declared above

foreach($php_assoc_array as $key => $value)
{
echo $key ." => ". $value ."<br/ >" ;
}
?>

/*** OUTPUT ***/

lang => PHP
c_type => ASSOCIATIVE
p_type => ARRAY

PHP Multidimensional Array Syntax:


<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTIDIMENSIONAL", "p_type"=>"ARRAY"));

//Iterate through an array declared above

foreach($php_multi_array as $key => $value)
{
if (!is_array($value))
{
echo $key ." => ". $value ."<br/ >" ;
}
else
{
echo $key ." => array( <br/ >";

foreach ($value as $key2 => $value2)
{
echo $key2 ." => ". $value2 ."<br/ >";
}

echo ")";
}
}
?>

/*** OUTPUT ***/

lang => PHP
type => array(
c_type => MULTIDIMENSIONAL
p_type => ARRAY
)

Note:
1- PHP count() Function is used to count elements in array.
2- PHP is_array() Function is used to check whether a variable is an array or not.

3 comments

  1. Pingback: PHP is_array() Function Example | PHP Tutors
  2. Pingback: PHP count() Function Example | PHP Tutors
  3. Pingback: PHP array_diff() Function Example | PHP Tutors

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s