top of page

What is an Associative Array In PHP? | PHP Assignment Help

First we need to discuss simple Array:

I can use one array for all my keys:

$student_info_keys = [

I can use one array for all my data:

$students = [
  ['Shaun McKinnon', 41, '12-22-1978'],
  ['Gagandeep Kaur', 23, '01-02-1997'],
  ['Sam Whitaker', 20, '05-17-1999']

But there are some potential issues!!!

  1. Order is imperative: if the order of either the student_info_keys or the students arrays change so they don't match, the data will corrupted!

  2. Quantity is crucial: The students array requires nested array to contain the same number of items. If we have a student with more information, the application will break!

To overcome these issues use the Associative Arrays:

Associative Arrays!

Associative arrays allow us to explicitly define keys in our array. Let's look at a normal array data structure:

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

Each value is indexed using a number. This is common to most programming languages. However, remember our rule: ALL ARRAYS IN PHP ARE ASSOCIATIVE ARRAYS. This means those indices are actually KEYS. This means they don't have to be numbers if we don't want them to be numbers!Our data structure can also look like this:

  "first" => "first value",
  "second" => "second value",
  "third" => "third value

Let's change our Student Application to use associative arrays:

// 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'

Fun facts about associative arrays-

  • Associative arrays use the same functions standard arrays do (because standard arrays are really just associative arrays with numerical keys)

  • Associative arrays can use whatever string key you want to make, including ones with spaces!

  • Associative arrays are the equivalent to JavaScript JSON structures and can be converted into JSON

  • Associative arrays are the default data structure returned by MySQL queries in PHP

3 views0 comments

Recent Posts

See All
bottom of page