Charleen Xen
Charleen Xen

Reputation: 33

Output an Array in PHP , array inside an array

I only want to output an array, first look at my code

CODE:

$shopping = array();
$shopping["john"] = "notebook1";
$shopping["john"] = "notebook2";
$shopping["doe"] = "notebook3";

echo '<pre>';
print_r($shopping);
echo '</pre>';

OUTPUT

    Array
(
    [john] => notebook2
    [doe] => notebook3
)

But I want my output to be like this:

    Array('john'=>array('notebook1','notebook2'),'doe'=>'notebook3');

How Can I achieve this?

Upvotes: 2

Views: 71

Answers (3)

AymDev
AymDev

Reputation: 7554

Actually, $shopping["john"] is a String.You need to declare it as an array. You can create your main array all in one:

$shopping = array(
    "john" => array(
        "notebook1",
        "notebook2"
    ),
    "doe" => "notebook3"
);

If using PHP 5.4 you can use the short array syntax:

$shopping = [
    "john" => [
        "notebook1",
        "notebook2"
    ],
    "doe" => "notebook3"
];

With this syntax you can use the shorthand to add an item to an array:

$shopping["john"][] = "notebook4";

/*
RESULT:
[john] => Array
    (
        [0] => notebook1
        [1] => notebook2
        [2] => notebook4
    )
*/

Upvotes: 0

HamzaNig
HamzaNig

Reputation: 1029

You need to add []= not just = try this :

$shopping = array();
$shopping["john"][] = "notebook1";
$shopping["john"][] = "notebook2";
$shopping["doe"][] = "notebook3";

echo '<pre>';
print_r($shopping);
echo '</pre>';

Upvotes: 3

Jason K
Jason K

Reputation: 1381

Just need to assign $shopping["john"] to an array.

$shopping["john"] = array("notebook1", "notebook2");
$shopping["doe"] = "notebook3";

Upvotes: 1

Related Questions