0

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";
1
  • 1
    btw: why quote the values? Although PHP does the type casting automatically if you calculate with the values later, it's good coding style to treat numbers as numbers like $money['Nickels'] = 5; Commented Nov 25, 2009 at 9:11

7 Answers 7

3

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";
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Did not see the echo, I was like how do I get my $money, thanks
1

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');

Comments

0

Yes that's fine.

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

Comments

0

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

Comments

0

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";

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.