Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Simple PHP Application Listing Inventory Items Displaying All Products

 Tony Mikel
 Tony Mikel
10,661 Points

Assigning keys to values

When assigning a key to a value in an array, like the following..

<?php  
$array[0] = "value";  
$array["key"] = "value";
?>  

Can you still reach the value in $array["key"] by using the index 0? I'm sure that's not very practical but I was just curious and couldn't find the answer anywhere else.

1 Answer

LaVaughn Haynes
LaVaughn Haynes
12,397 Points

No. You can only get to $array["key"] with $array["key"]. You have to use the key as with an associative array.

<?php 

    $array[0] = "value 1";  
    $array["key"] = "value 2";

    print_r( $array );
    // Array ( [0] => value 1 [key] => value 2 )

    echo $array[0];
    // value 1

    echo $array["key"];
    // value 2

?> 

If you push a new value into the array though it will pick up with the next numerical index though.

<?php

    $array[0] = "value 1";  // 0
    $array["key"] = "value 2"; // key

    // add new value to the end
    array_push($array, "value 3"); // 1

    print_r( $array );
    // Array ( [0] => value 1 [key] => value 2 [1] => value 3 )

    echo $array[1];
    // value 3
?>
LaVaughn Haynes
LaVaughn Haynes
12,397 Points

Technically you can convert $array to a numerically indexed array and access "value 2" using a number but you would lose that relationship to "key". I didn't think that's what you were asking though.

<?php 

    $array[0] = "value 1";  
    $array["key"] = "value 2";

    // convert keys to numbers
    $newArray = array_values( $array );

    print_r( $newArray );
    // Array ( [0] => value 1 [1] => value 2 ) 

?> 
 Tony Mikel
 Tony Mikel
10,661 Points

You answered my question. Thank you!