PHP Create Indexed Array
In this chapter you will learn:
- What is Indexed Array and how to create Indexed Array
- Create a PHP array
- Example to create PHP Array
- 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:
- What is a PHP Associative Array
- Syntax to create PHP Associative Array
- Example of a PHP Associative Array
- Example - Create Associative Array with different type of values