phparraysassociative-arrayassign

How to declare associative elements in an array?


I have

$test = array();
        
if (isset($ln[8])) {
    $test[] .= $id[0] . '=>' . $ln[14];
}    

But it puts the array like this

array (
    [0]=> 6525 => 120
    [1]=> 6521 => 1243
    [2]=> 5214 => 1674
    [3]=> 6528 => 155
)

whereas I want it to do this

array (
    6525 => 120
    6521 => 1243
    5214 => 1674
    6528 => 155
)

How would I do that.


Solution

  • What you are doing is adding a string consisting of, e.g., "6525 => 120" to each element in the array. What you really want to do is add the value from $lan[14] (e.g., the integer value 120) to the position $id[0] (e.g., 6525). This is how you do that with regular array syntax:

    $test[$id[0]] = $ln[14];
    

    Note how I treat $id[0] as the key to the $test array. It could have been the integer 6265, a string with value "hello", a variable called $key, a function call, or in this case an element from another array.