0

So I am using this code to push new user IDs into an array but I get

Warning: array_push() expects at least 2 parameters, one given

$post_likes = array(
"Some key" => array(
             'date' => date("d/m/Y"), 
             'IP' => get_client_ip())
             ); 
$new_likes = array(
             'date' => date("d/m/Y"), 
             'IP' => get_client_ip());
array_push($post_likes[$current_user->ID] = $new_likes);

The code works. It pushes new key with array value into the previous array. But still I get that warning. What am I missing?

7
  • 1
    Check this link. php.net/manual/en/function.array-push.php Commented May 7, 2018 at 5:22
  • I checked. Without using array push, it doesn't give me warning. But to use array push with key and value, they wrote this same thing. Also see the ans here - stackoverflow.com/questions/2121548/… used same method. But how come I get a warning? Could you please explain? Commented May 7, 2018 at 5:26
  • Check my answer below. I think you didn't check properly. Commented May 7, 2018 at 5:30
  • Have you tried just doing $post_likes[$current_user->ID] = $new_likes; without the array_push() at all? That will add a new key (the user ID) to the array with the $new_likes as value. Commented May 7, 2018 at 5:31
  • Yes I tried and it worked. Check my previous comment. @Magnus Eriksson I just wanted to know why this warning Commented May 7, 2018 at 5:33

2 Answers 2

2

Instead of using array_push() you can directly do like this-

$post_likes[$current_user->ID] = $new_likes;

A sample hardcoded example:- https://eval.in/1000261

Sign up to request clarification or add additional context in comments.

Comments

-1

Set your new variable $new_likes as like this:

array_push($post_likes[$current_user->ID] = $new_likes,$new_likes);   //expects at least 2 parameters

More info : http://php.net/manual/en/function.array-push.php

Updated:

I am proffering and suggesting to use @Magnus Eriksson's answer though you have accepted my answer.

So, just use as like below:

$post_likes[$current_user->ID] = $new_likes;

4 Comments

This might work, but it will throw a Notice, since array_push() wants the the first argument to be passed as reference (and there for wants an array, not the result of an expression).
@Magnus Eriksson Didn't show any notice. But I am still wondering, why!
@AsifurRahman - If it doesn't show a notice, it's because your error reporting hides notices. Demo: 3v4l.org/ot2Xu. This is the wrong way of doing it. You should accept Alivetodies's answer instead, since that's the correct way.
@Magnus Eriksson Oh didn't try it outside my environment. Thank you.

Your Answer

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