PHP Create Indexed Array

In this chapter you will learn:

  1. What is Indexed Array and how to create Indexed Array
  2. Create a PHP array
  3. Example to create PHP Array
  4. Array interpolation

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/*from   j a  v a2  s .  co 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.

Next chapter...

What you will learn in the next chapter:

  1. What is a PHP Associative Array
  2. Syntax to create PHP Associative Array
  3. Example of a PHP Associative Array
  4. Example - Create Associative Array with different type of values
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array