Question

Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.

EDIT -------

following Tristan's lead, I made this simple function to easily write in json in php. It will even take on variable from within your php as the whole thing is enclosed in quotes.

$one = 'newOne';
$json = "{
    '$one': 1,
    'two': 2
}";

// doesn't work as json_decode expects quotes.
print_r(json_decode($json));

// this does work as it replaces all the single quotes before 
// using json decode.
print_r(jsonToArray($json));

function jsonToArray($str){
    return json_decode(preg_replace('/\'/', '"', $str), true);
}
Was it helpful?

Solution

In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.

This means that you can use an array whichever way you please.

If you wanted an indexed array..

$indexedArray = array();

$indexedArray[] = 4; // Append a value to the array.

echo $indexedArray[0]; // Access the value at the 0th index.

Or even..

$indexedArray = [0, 10, 12, 8];

echo $indexedArray[3]; // Outputs 8.

If you want to use non integer keys with your array, you simply specify them.

$assocArray = ['foo' => 'bar'];

echo $assocArray['foo']; // Outputs bar.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top