Jim L
Jim L

Reputation: 351

How to use a number attached to a string in associative array

I have a card deck array:

$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);

And I want to echo the name of the card somewhere (example: 2_of_hearts) but also calculate something with the number attached to it, but I really can't seem to make it work. Also, I was unable to find a working answer for me.

Does anyone know how to do this?

Upvotes: 2

Views: 67

Answers (2)

Accountant م
Accountant م

Reputation: 7523

using this syntax of foreach lets you get access to the keys of the array

$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
foreach($cards as $key=> $value){
    $key = explode("_",$key);
    $cardname = $key[count($key)-1];
    //echo $key[0] . " of " $cardname . "<br>";
    echo $value . " of " $cardname . "<br>"; // edit after comments
}

NOTE: this is off-course if you sure your keys are always has the pattern #_of_cardname

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94672

If you use a foreach loop that provides you with the key and the value like this, you get both the 2_of hearts and the 2 as variables.

$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
foreach ( $cards as $name => $value) {
    echo $name . ' has a value of ' . $value.PHP_EOL;
    $calc = $value + 5;
    echo 'ADDED 5 - gives ' . $calc . PHP_EOL;
}

Result

2_of hearts has a value of 2
ADDED 5 - gives 7
3_of_hearts has a value of 3
ADDED 5 - gives 8
king_of_hearts has a value of 10
ADDED 5 - gives 15

Then you just do your calculation with the $value variable

Upvotes: 1

Related Questions