ArrayinPHPpptx 2024 10 17 19 09 22
ArrayinPHPpptx 2024 10 17 19 09 22
ArrayinPHPpptx 2024 10 17 19 09 22
An array is a data structure that stores one or more data values having
some relation among them, in a single variable. For example, if you
want to store the marks of 10 students in a class, then instead of
defining 10 different variables, it’s easy to define an array of 10 length.
Arrays in PHP behave a little differently than the arrays in C, as PHP is a
dynamically typed language as against C which is a statically type
language.
• An array in PHP is an ordered map that associates values to keys.
• A PHP array can be used to implement different data structures such
as a stack, queue, list (vector), hash table, dictionary, etc.
• The value part of an array element can be other arrays. This fact can
be used to implement tree data structure and multidimensional
arrays.
There are two ways to declare an array in PHP. One is to use the built-in
array() function, and the other is to use a shorter syntax where the
array elements are put inside square brackets.
array() Function: The built-in array() function uses the parameters given
to it and returns an object of array type. One or more comma-
separated parameters are the elements in the array.
array(mixed ...$values)
Each value in the parenthesis may be either a singular value (it may be
a number, string, any object or even another array), or a key-value pair.
The association between the key and its value is denoted by the "=>"
symbol.
Examples:
• $arr1 = array(10, "asd", 1.55, true);
• $arr2 = array("one"=>1, "two"=>2, "three"=>3);
• $arr3 = array(array(10, 20, 30), array("Ten", "Twenty", "Thirty"),
array("physics"=>70, "chemistry"=>80, "maths"=>90));
2. Using Square Brackets [ ]: Instead of the array() function, the comma-
separated array elements may also be put inside the square brackets to
declare an array object. In this case too, the elements may be singular
values or a string or another array.
var_dump($arr1[1]);
var_dump($arr2["two"]);
?>
Example-4
<?php
$numbers = array(10, 20, 30, 40,
50);