2

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?

3 Answers 3

3

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>';
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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
    )
*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.