Why is PHP prepending a numerical index to my associative array?

56 views Asked by At

When I use this code,

$views = array();
$views[]=['somevalue'=>'customerview.php'];
$views[]=['anothervalue'=>'ordersview.php'];

I get this,

Array
(
    [0] => Array
        (
            [somevalue] => customerview.php
        )

    [1] => Array
        (
            [anothervalue] => ordersview.php
        )

)

How can I make it get rid of the initial array without using array_shift or the like? Why is it putting the numerical array in the first place instead of just this,

Array
(
    [somevalue] => customerview.php
    [anothervalue] => ordersview.php

)

EDIT: How can I use the short syntax for this? Is that possible?

3

There are 3 answers

0
jt bullitt On BEST ANSWER

When you do this:

$views[] = ['somevalue' => 'customerview.php'];

you're saying, "Push another element onto the array, and assign to it the following value:

'somevalue' => 'customerview.php'

But this quantity is an array key and an array value. So what you're doing is inserting into your $views array a single element that itself contains an array key and array value. This explains the behavior you're seeing.

This should give you the results you want:

$views = array();
$views['somevalue'] = 'customerview.php';
$views['anothervalue'] ='ordersview.php';

Or, in shorthand:

$views = [
   'somevalue' => 'customerview.php',
   'anothervalue' => 'ordersview.php'
];
0
Nikola Zivkovic On

or you can do:

    $value1 = 'first';
    $value2 = 'second';

    $array = array(
        $value1 => 'customerview.php',
        $value2 => 'ordersview.php'
    );
0
Lloyd Banks On

$views is already an array so when you use $views[], you are adding another array into the existing array.

You need to use

$views = array(
    'somevalue' => 'customerview.php',
    'anothervalue' => 'ordersview.php'
)