Array datatype in PHP

How to define an array variable and assign value?


An array is a compound data type that can contain multiple data values. Each array element can be retrieved by using the array variable name and its key/index value. The index value may be either numeric value or string value.
An array variable can be declared as
$arrayname = array( "first element", 2,$val );
echo $arrayname[0]; //prints: first element
echo $arrayname[1]; //prints: 2
echo $arrayname[2]; //prints: 3

Array values can hold values with different data type. As you see in the previous example, elements in an array can be any data type(string, integer, double). Array index always starts at position zero,so the first array element has an index of 0 and the last element has an index one less than the number of elements in the array. You can also use print_r($arrayname) function to print the values of an array.
PHP allows you to add an element at the end of an array without specifying an index.

For example:

$arrayname[] ="Test";

In this case, the "Test" element is given the index 3 in our $arrayname array. If the array has non-consecutive elements, PHP selects the index value that is one greater than the current highest index value.
Arrays indexed using strings are called as associative arrays



we cannot use a simple counter in a for loop to work with this array. We can use the foreach loop or print_r() function. In the following example we use the foreach loop to iterate through our associative array.
foreach($arr as $arrval=>$val)
echo "$val";

PHP Topics

Ask Questions

Ask Question