PHP Array

What is PHP array?

There are several basic variable types in PHP. Array is one of them. As everybody know due to its dynamic nature PHP does not require type definitions, and variables automatically appear when you mention them for the first time, and can change their type during execution.

Internally, PHP array, unlike array variables in classic static languages like C, is not a sequence of elements of one predefined type. PHP array is a hash table representing a reflection of keys to their values, where values can belong to any type. That is why you can easily modify PHP arrays, insert and remove their elements without need to repack the arrays' internal memory chunks. However, access time for PHP array remains O(1).

Despite the fact that PHP array is a hash, it has its beginning and its end. The keys which were defined first are closer to the beginning.

Basic PHP array functions

To point a PHP variable as array you should use the array() construction function.

  1. <?php
  2.  
  3. $myArray = array();
  4.  
  5. ?>

The example above creates $myArray variable as an empty PHP array.

In general the construction looks like:

  1. <?php
  2.  
  3. [key1] => value1,
  4. [key2] => value2,
  5. ...
  6. [keyN] => valueN
  7. );
  8.  
  9. ?>

For example:

  1. <?php
  2.  
  3. $userInfo = array(
  4. "name" => "John",
  5. "surname" => "Smith",
  6. "age" => 33,
  7. "sex" => "m",
  8. "children" =>
  9. "Mary", "Brandon", "Lora"
  10. )
  11. );
  12.  
  13. ?>

Key values in PHP array() function are optional. You can omit them. In this case PHP automatically assigns integer values starting with 0 to the array's keys. The following calls are equal:

  1. <?php
  2.  
  3. $PHPArray = array( 0 => "Banana", 1 => "Apple", 2 => "Pear" );
  4. $PHPArray = array( "Banana", "Apple", "Pear" );
  5.  
  6. ?>

If you skip some of the keys PHP will set them using the previously defined keys. The following calls are equal:

  1. <?php
  2.  
  3. $PHPArray = array( "Banana", 5 => "Apple", "Orange", "Сoconut", 10 => "Pear", "Cherry" );
  4. $PHPArray = array( 0 => "Banana", 5 => "Apple", 6 => "Orange", 7 => "Сoconut", 10 => "Pear", 11 => "Cherry" );
  5.  
  6. ?>

Check variable

You can always check whether a PHP variable is an array or not with help of is_array() function. It returns boolean true/false values which are usually used in conditions.

  1. <?php
  2.  
  3. if ( is_array( array() ) )
  4. echo "This is an array"; // Prints "This is an array"
  5. else echo "This is not an array";
  6.  
  7. ?>

Access PHP array values

PHP uses the same syntax most popular languages use to access array values.

  1. <?php
  2.  
  3. $PHPArray = array(
  4. "name" => "John",
  5. "surname" => "Smith",
  6. "age" => 33,
  7. "sex" => "m"
  8. );
  9.  
  10. $PHPArray[ "children"] = array( "Mary", "Brandon", "Lora" ); // Now the $PHPArray variable is equal to the $userInfo variable mentioned earlier.
  11. $surname = $PHPArray[ "surname" ]; // $surname contains "Smith"
  12. $lora = $PHPArray[ "children"][ 2 ]; // $lora contains "Lora"
  13.  
  14. ?>

Put new variables into PHP array

There are several ways to add new values to array. The main is setting new value by key as shown in the example above where we added "children" key pointing to a newly created array of children's names.

The second way is operator []= which appends a new element to the end of array:

  1. <?php
  2.  
  3. $PHPArray = array( 0 => "Banana", 5 => "Apple" );
  4. $PHPArray []= "Orange";
  5. // Now $PHPArray contains array( 0 => "Banana", 5 => "Apple", 6 => "Orange" );
  6.  
  7. ?>

The third way is using functions like array_merge() and array_merge_recursive(), and + operator.

Get count of PHP array's elements

To find out how many elements there are in an array use count() function. It returns the amount of the first-level's elements.

  1. <?php
  2.  
  3. $userInfo = array(
  4. "name" => "John",
  5. "surname" => "Smith",
  6. "age" => 33,
  7. "sex" => "m",
  8. "children" =>
  9. "Mary", "Brandon", "Lora"
  10. )
  11. );
  12.  
  13. $count = count($userInfo ); // $count contains 5 ( reflects the count of keys "name", "surname", "age", "sex", "children")
  14.  
  15. ?>

Traveling through PHP array

If the array's keys are integers without gaps then the simplest way to go through it is for operator.

  1. <?php
  2.  
  3. $PHPArray = array( "Banana", "Apple", "Pear" );
  4. for ( $index = 0; $index < count( $PHPArray ); $index++ )
  5. $elementValue = $PHPArray[ $index ]; // $elementValue changes values from "Banana" to "Pear"
  6.  
  7. // $elementValue contains "Pear"
  8.  
  9. ?>

There is more advanced and more powerful foreach operator which covers all kinds of standard PHP arrays.

  1. <?php
  2.  
  3. $userInfo = array(
  4. "name" => "John",
  5. "surname" => "Smith",
  6. "age" => 33,
  7. "sex" => "m"
  8. );
  9.  
  10. foreach ( $userInfo as $elementValue ); // $elementValue changes from "John" to "m"
  11. // $elementValue contains "m"
  12.  
  13. ?>

If you wish to get keys of your PHP array inside foreach together with the values use the following foreach syntax:

  1. <?php
  2.  
  3. $userInfo = array(
  4. "name" => "John",
  5. "surname" => "Smith",
  6. "age" => 33,
  7. "sex" => "m"
  8. );
  9.  
  10. foreach ( $userInfo as $elementKey => $elementValue ); // $ elementKey changes from "name" to "sex", the behavior of $elementValue remains the same as in the previous example
  11. // $elementKey contains "sex", $elementValue contains "m"
  12.  
  13. ?>

Both versions of foreach shown above iterate arrays getting $elementValue by value, which means that changing $elementValue inside foreach does not affect $userInfo itself. To get direct access to PHP array's values use the following syntax (mention the & sign):

  1. <?php
  2.  
  3. $PHPArray = array(
  4. "name" => "John",
  5. "surname" => "Smith",
  6. "age" => 33,
  7. "sex" => "m",
  8. );
  9.  
  10. // modify the $PHPArray so that all keys will point to the strings held in the keys themselves ( "name" => "name", "surname" => "surname" : )
  11. foreach ($PHPArray as $elementKey => &$elementValue )
  12. $elementValue = $elementKey;
  13.  
  14. ?>

Another way to iterate PHP arrays is the combination of reset(), list() and each() functions inside for operator. Here is how it looks like:

  1. <?php
  2.  
  3. for ( reset( $PHPArray ); list( $elementKey, $elementValue ) = each( $PHPArray ); );
  4.  
  5. ?>

Bookmark this page

bookmark in your browserbookmark at mister wongpublish in twitterbookmark at del.icio.usbookmark at digg.combookmark at furl.netbookmark at linksilo.debookmark at reddit.combookmark at spurl.netbookmark at technorati.combookmark at google.combookmark at yahoo.combookmark at facebook.combookmark at stumbleupon.combookmark at propeller.combookmark at newsvine.combookmark at jumptags.com

Rate this content

Submitting your vote...
Rating: 5.0 of 5. 2 vote(s).
Click the rating bar to rate this item.

User comments

No comments

Add comment

* - required field

*
*




*
*

Search the site

 
Enter your username and password here in order to log in on the website:

Latest News

Friday, 07 August, 2009

Is Google Voice a Threat to AT & T?

Google Voice

Our story so far: Chapter 1: Apple creates the iPhone. Chapter 2: Apple opens the App Store, an online catalog of cheap or free programs that you can download straight to the phone. Programmers all over the world write 70,000 apps for it that... read more...

Friday, 07 August, 2009

Apple Releases Mac OS X Leopard Update

Mac OS X Leopard

Apple released a Mac OS X Leopard upgrade that brings better stability and security to the operating system and improves compatibility with AirPort wireless networks and other Apple technology. Mac OS X 10.5.8 was made available from Apple on... read more...

Friday, 07 August, 2009

Telco Planning joins the Linux Foundation

Telco Planning has joined The Linux Foundation, the nonprofit organization dedicated to accelerating the growth of Linux. Telco Planning provides consulting services to network operators that encompass technology evaluation, business plan modeling,... read more...

Friday, 07 August, 2009

The ins and outs of DoS attacks

DDoS

Thursday's denial-of-service attack that knocked Twitter offline for a few hours and affected Facebook, LiveJournal, and Google Sites and Blogger wasn't your average attack. Typically, someone who has a bone to pick with a specific Web site will... read more...

Latest Articles

Monday, 10 August, 2009

PHP array

PHP array

There are several basic variable types in PHP. Array is one of them. As everybody know due to its dynamic nature PHP does not require type definitions, and variables automatically appear when you mention them for the first time, and can change their... read more...

Thursday, 06 August, 2009

What is Symantec Corporation

Symantec Corporation was founded in 1982 by Gary Hendrix with a National Science Foundation grant. Symantec was originally focused on artificial intelligence-related projects, including a database program. Hendrix hired several Stanford University... read more...

Thursday, 06 August, 2009

What is IBM

What is IBM...

International Business Machines Corporation, abbreviated IBM and nicknamed "Big Blue" (for its official corporate color), is a multinational computer technology and IT consulting corporation headquartered in Armonk, New York, United... read more...

Thursday, 06 August, 2009

What is Apple Inc

What is Apple Inc...

Apple Inc. is an American multinational corporation that designs and manufactures consumer electronics and computer software products. The company's best-known hardware products include Macintosh computers, the iPod and the iPhone. Apple software... read more...

Thursday, 06 August, 2009

What is Oracle Corporation

Oracle is...

Oracle Corporation specializes in developing and marketing enterprise software products - particularly database management systems. Through organic growth and a number of high-profile acquisitions, Oracle enlarged its share of the software market.... read more...