wiki:Php Arrays

php Arrays

There are two main types of arrays in php, indexed and associative.

Indexed Arrays

These are valid:

<?php
	$arr = array(1, 2, 3, 4, 5);

	echo $arr[0]; // 1

//to access the elements in a foreach loop (for and while loops same as C)

foreach($arr as $e)
{
	echo ' '. $e;
}
//output: 1 2 3 4 5

?>

Associative Arrays

They are key-value pairs using the double arrow in the form 'key'=>'value'

Note how the different data types are handled:

<?php
	$arr = array(
		"foo" => "bar", 
		12 => true
	);

	echo $arr["foo"]; // bar
	echo $arr[12];    // 1

// in a foreach loop
foreach($arr as $key=>$value)
{
	echo $key. ':' .$value. '|';
}

//output:foo:bar|12:1
?>

More complicated examples can be found at: http://www.php.net/manual/en/language.types.array.php


PHP native array functions of interest

bool in_array ( mixed $needle , array $haystack [, bool $strict ] )

Returns boolean if $needle is in $haystack

<?php
	$os = array("Mac", "NT", "Irix", "Linux");
	if (in_array("Irix", $os)) {
		echo "Got Irix";
	}
	if (in_array("mac", $os)) {
		echo "Got mac";
	}
?>

int count ( mixed $var [, int $mode = COUNT_NORMAL ] )

<?php
	$a[0] = 1;
	$a[1] = 3;
	$a[2] = 5;
	$result = count($a);
	// $result == 3

	$b[0]  = 7;
	$b[5]  = 9;
	$b[10] = 11;
	$result = count($b);
	// $result == 3

	$result = count(null);
	// $result == 0

	$result = count(false);
	// $result == 1
?>

mixed array_shift ( array &$array )

Shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

<?php
	$stack = array("orange", "banana", "apple", "raspberry");
	$fruit = array_shift($stack); //$fruit would contain "orange"
	print_r($stack);
?>

Notice, if you don't want to do a loop to print the array, you can use print_r($arr). The above would output:

(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

Here are the rest of the native php array functions: http://www.php.net/manual/en/ref.array.php

Last modified 7 years ago Last modified on Mar 17, 2011, 7:49:22 PM