Yogesh Chauhan's Blog

3 Types of Arrays in PHP

in PHP on November 26, 2019

There are 3 types of arrays in PHP.

  • Indexed arrays
  • Associative arrays
  • Multidimensional arrays

Indexed arrays

These are the arrays with a numeric index and there are 2 ways to create this type of arrays.

Automatic Indexing:


$hobbies= array("Reading", "Sports", "Guitar");

Or Manual Indexing:


$hobbies[0] = "Reading";
$hobbies[0] =  "Sports";
$hobbies[0] = "Guitar";

Take a look at the example in the DEMO link given at the end of this article.

Associative Arrays

This type of arrays use named keys assigned to them by us and there are 2 ways to create this type of arrays same as the indexed arrays.


$age = array("Yogi"=>"28", "Hulk"=>"56", "Captain"=>"34");

OR


$age['Yogi'] = "28";
$age['Hulk'] = "56";
$age['Captain'] = "34";

Multidimensional Arrays

Multidimensional Arrays contain one or more arrays inside.

Lets take a look at the example:

Let's say we have a table like this:

Name Stock Sold
Members Mark 22 18
Dasani 15 13
Bubly 5 2
Aqua 17 15

We can store the data above in the 2 dimensional array like this:


$water = array
  (
  array("Members Mark",22,18),
  array("Dasani",15,13),
  array("Bubly",5,2),
  array("Aqua",17,15)
  );

And we can get the values from the array like this:


echo "We have ". $water[0][0]. " water " .$water[0][1]. " in stock and we have sold " . " ".$water[0][2]." bottles today.<br>";

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
SQL GROUP BY StatementSQL/MySQLWhat are components in Angular?AngularWhat’s the difference between a Framework and a Library?MiscellaneousWordPress: How to access first and random row values from a repeater field in ACF?WordPressHow to create a horizontal scrolling menu with and without flex using CSS (or SCSS)?CSSHow to create a Progress Bar using JavaScript?JavaScript