Differents Types Of Arrays With Examples Using PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

An array is a data structure that stores one or more similar type of values in a single variable.

array and its types in php

Array
for example
If you have collection of items and that  storing in single variables:

$birds_1="crow";
$birds_2="peacock";
$birds_3="sparrow";

if we have 100 of birds we can not declare new variable for every birds so to over come this problem. we use array in one $birds variable  we can store all collection of birds in it.

Create an array in php

array();

$birds = array("crow", "peacock", "sparrow");//define array


There are three types of arrays:


Example for Indexed arrays:

<?php
// Define an indexed array
$birds = array("crow", "peacock", "sparrow");
?>

or

<?php

$birds[0] = "crow";
$birds[1] = "peacock";
$birds[2] = "sparrow";
?>


Example for Associative arrays:

<?php
// Define an associative array
$bike = array("bike-1"=>22, "bike-2"=>32, "bike-3"=>28);
?>

or

<?php
$bike["bike-1"] = "22";
$bike["bike-2"] = "32";
$bike["bike-3"] = "28";
?>


Example for Multidimensional arrays:

<?php
// Define a multidimensional array
$details = array(
    array(
        "name" => "john Parker",
        "dob" => "1998/05/01",
        "email" => "johnparker@mail.com",
    ),
    array(
        "name" => "jeo",
        "dob" => "1997/06/11",
        "email" => "jeo@mail.com",
    ),
    array(
        "name" => "Harry",
        "dob" => "1995/04/18",
        "email" => "harry@mail.com",
    )
);
// Access nested value
echo "john Parker's Email-id is: " . $details[0]["email"];
?>



Displaying Array Structure and Values:
the structure and values of any array by using one of two statements — var_dump() or print_r().
for example:

<?php 
$birds = array("crow", "peacock", "sparrow");
print_r($birds);
?>

 

We can also get the length of an Array  using count() Function

The count() function is used to return the length  of an array:

<?php
$birds = array("crow", "peacock", "sparrow");
echo count($birds);
?>


Complete Code of An  Array:

<!DOCTYPE html>
<html>
<head>
    <title>array and its types in php</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Array and its types in PHP</h1>
    </div>
    <br>
    <br>
    <br>
    <h2>An array is a data structure that stores one or more similar type of values in a single variable.</h2>
    <div class="well">
        <?php
        $birds = array("crow", "peacock", "sparrow");
        echo "<p>length of array elements</p>".count($birds);
        echo "<br>";
        echo "<br>";
        print_r($birds);
        ?>
    </div>

    <br>
</div>
</body>
</html>

Related Post