HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Create Arrays

You can create arrays by using the array() function:

Example

<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>  

</pre>
</body>
</html>


Output

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

• Multiple Lines

Line breaks are not important, so an array declaration can span multiple lines:


Example

<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = [
  "Volvo",
  "BMW",
  "Toyota"
];
var_dump($cars);
?>  

</pre>
</body>
</html>


Output

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}

• Trailing Comma

A comma after the last item is allowed:


Example

<!DOCTYPE html>
<html>
<body>
<pre>

<?php  
$cars = [
  "Volvo",
  "BMW",
  "Toyota",
];
var_dump($cars);
?>  

</pre>
</body>
</html>



Output

array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}


• Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a foreach loop, like this:


Example


Display all array items:

<!DOCTYPE html>
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota"); 

foreach ($cars as $x) {
  echo "$x 
"; } ?> </body> </html>

Output

Volvo
BMW
Toyota