简体   繁体   中英

PHP, how to access value in associative array when key is an int

I have an array like this:

$sizing = array(
    "4" => "US 4 - EU XXS",
    "5" => "US 5 - EU XS",
    "6" => "US 6 - EU S",
    "7" => "US 7 - EU M",
    "8" => "US 8 - EU L",   
    );

Later in the code I need to find out the value from this array where the number is stored in $size

I'm trying

$new_size = $sizing["$size"];

but receive an error that

Notice: Undefined index: 4

I'm assuming this is because I'm using a number as the key and PHP thinks its referring to an index rather than a named key.

How can I do this better? Thank you.

Try this

 $sizing = array(
    4 => "US 4 - EU XXS",
    "US 5 - EU XS",
    "US 6 - EU S",
    "US 7 - EU M",
    "US 8 - EU L"   
    );
    $size = 4;    
    echo $sizing[$size]; //US 4 - EU XXS  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM