开发者

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";
$m开发者_如何学运维oney3['Quarters'] = "25";


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


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


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


Yes that's fine.

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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜