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

PHP Arrays

In PHP, arrays are a fundamental data structure used to store and manage collections of items of the same or different data types under a single variable name.


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"
}

• What is an Array?

An array is a collection of items, all of the same data type, stored at contiguous memory locations and accessed using an index


• PHP Array Types

In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index

Associative arrays - Arrays with named keys

Multidimensional arrays - Arrays containing one or more array



• Working With Arrays

In this tutorial you will learn how to work with arrays, including:

Create Arrays
Access Arrays
Update Arrays
Remove Array Items
Sort Arrays



• Array Items

Array items can be of any data type.

The most common are strings and numbers (int, float), but array items can also be objects, functions or even arrays.

You can have different data types in the same array.


Example


Array items of four different data types:

<!DOCTYPE html>
<html>
<body>

<?php  
// function example:
function myFunction() {
  echo "This text comes from a function";
}

// create array:
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);

// calling the function from the array item:
$myArr[3]();
?>  

</body>
</html>

Output

This text comes from a function

• Array Functions

The real strength of PHP arrays are the built-in array functions, like the count() function for counting array items:


Example


How many items are in the $cars array:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

Output

3