phparrays

array_push won't give an array, prints out integer value


I'm doing a very simple php program with array_push, but it isn't working according to the documentation. Every time i try to print the value of the final array, it gives me an integer. Could someone please help me with this?

Here's my code:

<?php
    $preArray = array('1','2','3','4','5','6','7','8');
    $val = 10;
    $array = array_push($preArray, $val);

    print_r($array);
?>

This is what it outputs:

9

Solution

  • array_push() returns the new number of elements in the array. So if you're not interested in the number of elements in the array then just use:

    array_push($preArray, $val);
    

    The variable $preArray will contain the value pushed into it.

    print_r($preArray);