Main menu

15 minute php - Day 1

15 Jan
Published by Mark W. Breneman

Indexed Arrays

Indexed arrays in PHP are really simple. They are arrays that are referenced numerically by position starting with 0 as first position.

 

Create an indexed array:

$foo = array('red',"blue","green");

 

Item at position 1 can be addressed  by:

$foo[0]  (echo $foo[0];)

 

Item at position 2 can be addressed  by:

$foo[1]

 

Item at position 2 can be changed by:

$foo[1] = 'yellow';

 

var_dump is a good way to get a visual print out of the array. Note, in drupal I would use dpm / dsm for a much nicer looking print out.

var_dump($foo);

 

 

Check out:

current(),  next()prev()end() and reset()

There are lots of functions that can be used with indexed arrays. Here is a list of all of the php array functions,  not all functions in this list can be used with indexed arrays. )

http://us3.php.net/manual/en/ref.array.php

 

Questions:

What is the output of this code:

$foo = array('red',"blue","green");

echo next($foo);

 

 

What is the output of this code:

$foo = array('red',"blue","green");

$foo[3] = 'silver'; 

echo end($foo);

 

You can also put number into an indexed array:

$foo = array(1,100,5,45,8,9,10,45,23,56,2);

 

What is the output of this code:

$foo = array(1,100,5,45,8,9,10,45,23,56,2);

echo $foo[4];

 

We can count the number of items in the array:

Echo count($foo);

var_dump($foo);

 

We can sort them from smallest to largest:

Sort($foo);

var_dump($foo);

 

We can even add them up:

echo array_sum($foo) ;

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.