top of page

What Is Array And Nested Array In PHP? | PHP Assignment Help

PHP Variables

Variables are essentially containers that store a value.


Examples:

<?php
  $name = "Realcode4you"; // It is implied that this variable is a string
  $_valid_var = "Variables can have underscores.";
  $integer = 5; // It is implied that this variable is an integer
  $decimal = 5.1; // It is implied that this variable is a float value
  $bool = true; // It is implied that this variable is a boolean
  ?>

Above all variables are valid, now we see the some variable declaration which is not valid:

<?php
  $not-valid = "Realcode4you"; #not use dashes
  $not valid = "Naveen";       #not use space
  $2_var_php = "php";          #not use digit in starting
  $nav_ku_@$%^&* = "var";      # not use non-alphanumeric characters
  ?>

PHP Array

In PHP Array can be created using two ways:


// Using a function
$arr = array();

// Using an array literal
$arr = [];

Both ways are identical. They will both store an empty array into the variable $arr

// Initialize array into array using 4 item
$arr = array('a', 'b', 'c', 'd');

// Initialize array into array using 4 item
$arr = ['a', 'b', 'c', 'd'];

Array values aren't locked to one data type. In fact, an array can contain a variety of data:

// Arrays can have a list of any values of any data types
$arr = [true, "Naveen", 41, 35.63];


Adding new values to an array:

I can do this by using the array_push()function:

// Adding a value to the end of an array
array_push($arr, "I like cats");


Reading an array value

// Accessing index 1 element from the $arr array
echo $arr[1];

Nested Arrays

PHP also supports nested array structures.

// Nested array example
$arr = [41,"Shaun",["Diablo",    "3D Printing",    "nerd things"]];

Updating an array value

// Updating a value in an array
$arr[1] = "We are freelancer";
var_dump($arr);


What is an Associative Array:

Associative arrays allow us to explicitly define keys in our array.


[
0 => "first value",
1 => "second value",
2 => "third value
]


Example:

// Using associative arrays
$students = [
                [
                "name" => 'Shaun McKinnon',
                "age" => 41,
                "dob" => '12-22-1978'
                ],
                
                ["name" => 'Gagandeep Kaur',
                "age" => 23,
                "dob" => '01-02-1997'
                ],
                
                ["name" => 'Sam Whitaker',
                "age" => 20,
                "dob" => '05-17-1999'
                ]
           ];

Accessing element from associate array:

// Access Gagandeep's dob
echo $students[1]["dob"];

6 views0 comments
bottom of page