What's better to use in PHP, $array[] = $value or array_push($array, $value)?

前端 未结 10 1145
野性不改
野性不改 2020-12-02 01:28

What\'s better to use in PHP for appending an array member,

$array[] = $value;

or

array_push($array, $value);
相关标签:
10条回答
  • 2020-12-02 02:02

    One difference is that you can call array_push() with more than two parameters, i.e. you can push more than one element at a time to an array.

    $myArray = array();
    array_push($myArray, 1,2,3,4);
    echo join(',', $myArray);
    

    prints 1,2,3,4

    0 讨论(0)
  • 2020-12-02 02:02

    A simple $myarray[] declaration will be quicker as you are just pushing an item onto the stack of items due to the lack of overhead that a function would bring.

    0 讨论(0)
  • 2020-12-02 02:03

    Word on the street is that [] is faster because no overhead for the function call. Plus, no one really likes PHP's array functions...

    "Is it...haystack, needle....or is it needle haystack...ah, f*** it...[] = "

    0 讨论(0)
  • 2020-12-02 02:07

    Since "array_push" is a function and it called multiple times when it is inside the loop so it will allocate a memory into the stack. But when we are using $array[] = $value then we just assigning value to array.

    0 讨论(0)
  • 2020-12-02 02:09

    I just wan't to add : int array_push(...) return the new number of elements in the array (php doc). which can be useful and more compact than $myArray[] = ...; $total = count($myArray);.

    Also array_push(...) is meaningful when variable is used as stack.

    0 讨论(0)
  • 2020-12-02 02:13

    The main use of array_push() is that you can push multiple values onto the end of the array.

    It says in the documentation:

    If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

    0 讨论(0)
提交回复
热议问题