Php Function Returning Associate Array [Closed]

Php Function Returning Associate Array [Closed]

I would like to know how to make a function return an associative array. I am getting only values of the returned array but not keys

3

1 Answer

you need to set those keys yourself like. If not it adds automatically an index starting from 0. Have a look at my example

function myfunc(){
    $arr = array();
    $arr[] = 'value0';
    $arr['key1'] = 'value1';
    $arr['key2'] = 'value2';
    $arr[] = 'value3';
    return $arr;
}

that will output

// you see the first and fourth value has the index 0 and 1, 
// the other those that are defined
array(4) {
  [0]=>
  string(6) "value0"
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
  [1]=>
  string(6) "value3"
}
3
Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.