PHP Create Indexed Array

Description

Indexed arrays is arrays where each element is referenced by a numeric index, usually starting from zero. For example, the first element has an index of 0, the second has an index of 1, and so on

Syntax

PHP has built-in support for arrays, and we can create array using the array() function.

$myarray = array(element0, element1, element2,element3,...);

Example

Here is a basic example:


<?PHP// ww w. jav a  2 s. c  o  m
$myarray = array("PHP", "Java", "Python","java2s.com"); 
$size = count($myarray); 
print_r($myarray); 
?>

The code above generates the following result.

On the first line, we create an array, the array() function. array() function takes a list of variables or values as its parameters, and returns an array containing those variables.

In that example, $myarray contains three elements.

There are our three values-PHP is at index 0 in the array (signified by [0]=>), Java is at index 1 in the array, and Python is at index 2 in the array.

You can store whatever you like as values in an array, and you can also mix values. For example: array("Foo", 1, 9.9, "java2s.com", $somevar).

Array interpolation

To print array data inside a string, we have to use braces {} around the variable. This next code shows how.


<?PHP
$myarray['foo'] = "bar";
print "This is from an array: {$myarray['foo']}";
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone