-2
  1. $db["db_name"] = "users";

  2. $db_name = "users";

How will example 1 be different from example 2?

3 Answers3

1

The first is an array named db which has an element with index db_name; the second is a scalar named db_name.

Ray O'Donnell
  • 759
  • 4
  • 11
1

Let's try to break things down in order to simplify them.

  • $db["db_name"] = "users";: that would make $db an associative array where the string "db_name" is a key in that array and "users" is the value for the "db_name" key in the $db array. When you call echo $db["db_name"] the text users will be printed to the screen.

  • $db_name = "users";: that means that $db_name is a variable where "users" is its value. So when calling echo $db_name the result will be users (printed to the screen).

In PHP you can use a variable (its value to be precise) as an array index which allows you retrieve the value at that index from an array, an example:

$db_name = "users"; // this will act as an index
$db[$db_name] = "some value"; // the index "user" which is the value of the variable "$db_name" holds the value "some value" in the "$db" variable
echo $db_name . ' | ' . $db[$db_name]; // prints: users | some value

Here's a live demo for the code above.

So to summarize, $db["db_name"] = "users" create an array with "db_name" as a key in that array that holds the value "users" where the other one, $db_name = "users", create a variable that holds the string users.

ThS
  • 4,597
  • 2
  • 15
  • 27
0

Brackets are a way to print a value from an array.

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";