Newb
Newb

Reputation: 678

php associative array construct

Is this the proper construct of my wannabe associative array or is there a better method to this?

Each ID key is associated with a value, in this case ID is Nickels(index key) with a value of "5", assigned to the variable $money1.

$money1['Nickels'] = "5";
$money2['Dimes'] = "10";
$money3['Quarters'] = "25";

Upvotes: 0

Views: 326

Answers (7)

miku
miku

Reputation: 188164

Yes. It's correct. Assuming, you want to have 3 arrays in the end (money1, money2, money3).

If you want one array, you can use this compact notation:

$money = array("Nickels" => "5", "Dimes" => "10", "Quarters" => "25");

.. which is a shorter form of:

$money["Nickels"] = "5";
$money["Dimes"] = "10";
$money["Quarters"] = "25"

Array access:

echo $money["Dimes"]; // prints 10

Upvotes: 2

johannes
johannes

Reputation: 15989

A variable with a number looks like a flaw. And if you want integers you might remove the quotes around the numeric values. But without any details hard to say more.

Upvotes: 0

wallyk
wallyk

Reputation: 57794

What you have will be of use, but since you don't show any code, it's hard to say whether it will be of use to you.

Here are some other methods of containing the data which may be of use.

$money = array ('Nickels' => '5', 'Dimes' => '10', 'Quarters' => '25');

or

$money = array (5 => 'Nickels' , 10 => 'Dimes', 25 => 'Quarters');

Upvotes: 1

Tomas Markauskas
Tomas Markauskas

Reputation: 11596

It's not one array, but 3. Are you sure that you want to assign one value to each of the 3 arrays? It looks like you might want to assign those values to just one array:

$money['Nickels'] = "5";
$money['Dimes'] = "10";
$money['Quarters'] = "25";

Upvotes: 0

Ben Everard
Ben Everard

Reputation: 13804

Well that's three associative arrays, if you want a single associative array then you need to do this:

$money['Nickels'] = "5";
$money['Dimes'] = "10";
$money['Quarters'] = "25"

Or a shorter version:

$money=array('Nickels'=>'5','Dimes'=>'10','Quarters'=>'25');

If your looking for three different arrays, it's no better than doing this:

$Nickels = "5";
$Dimes = "10";
$Quarters = "25";

Upvotes: 3

pauljwilliams
pauljwilliams

Reputation: 19225

Well, that would work. Whether it is 'correct', or best practice depends on the problem you are trying to solve...

Upvotes: 0

Greg
Greg

Reputation: 321806

Yes that's fine.

A little inconsistent with the quoting, but it will work.

Upvotes: 0

Related Questions