0

I’m now learning PHP array but I have a question about the array operator. I saw an example when creating an array like this:

<?php
$array = array();
$array["a"] = "apple";
$array["b"] = "banana";
?>

Do I really need to declare the variable as array first?
Or can I just ignore the first line: $array = array();?

1

2 Answers 2

3

Better yet, just initialize your array and assign values to it at the same time:

<?php
    $array = array(
        "a" => "apple",
        "b" => "banana"
    );
?>
Sign up to request clarification or add additional context in comments.

2 Comments

What I'm trying to avoid is to do it like your example. I don't have a specific reason or maybe because I read somewhere that writing like this $array[], is more preferable, is this true?
Doing it this way will save you a dozen or so keystrokes. @Joey - A better method I think.
1

You don't need to initialize your arrays in PHP. In other words, you don't need $array = array();, but it will save you code to do it like @John Conde showed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.