0

I have array of data which looks like this:-

$a = array(
    array(
        'amount' => 1.2,
    ),
    array(
        'amount' => 0.53,
    ),
    array(
        'amount' => 25.2,
    )
);

and another array

$n = array(
    'amount' => 12.98,
);

and then I use array_push

$p = array_push($a,$n);
print_r($p);

But the end result I get is

4

I want the array to be like :-

array(
    array(
        'amount' => 1.2,
    ),
    array(
        'amount' => 0.53,
    ),
    array(
        'amount' => 25.2,
    ),
    array(
        'amount' => 12.98,
    )
);

What is thing which I am doing wrong? How can I fix it? Please help.

1
  • 2
    Open please a manual. Commented Aug 31, 2018 at 15:42

2 Answers 2

1

array_push pushes the second argument onto the array specified in the first argument. It returns the new number of elements, so:

array_push($a, $n);
print_r($a);

Or if you need a new array:

$p = array_merge($a, array($n));
print_r($p);

//or

$p = $a;
$p[] = $n;
print_r($p);

If a new array isn't needed, this is easier:

$a[] = $n;
print_r($a);
Sign up to request clarification or add additional context in comments.

Comments

0

This behaviour is normal as array_push()'s 1st argument is passed by reference and:

Returns the new number of elements in the array.

You just need to use it as:

array_push($a,$n);
echo '<pre>' . print_r($a, true) . '</pre>';

Or you could use the array_push shorthand:

$a[] = $n;

3 Comments

Of course it wasn't you, but I wonder why someone did it without any comment.
Before the edit is was the exact same as an existing answer, and that is not short array syntax and has always been available in PHP.
You are right about short array syntax, corrected this. We were probably typing at the same time. If I was downvoting for similar answers posted after mine every time I'd be downvoting a lot.

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.