0

I have

$userPostsInt = array("22", "45", "56");

I am receiving via ajax an id:

$post_id = $_POST['id'];

Then on front end I click and send an ID and I need to check if:

 1. the clicked ID is in the array
 2. if the array count is <= 2 if not do something

So I try:

$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if($count<2) {
  foreach($userPostsInt as $key=>$post){ 
    if( $post == $post_id ) { 
      foreach($userPostsInt as $idInt){ 
        array_push($totSaved, $idInt);
      }
      echo json_encode($count);
    }
  }
} else {
  echo json_encode($count); 
}

Then on ajax success I do:

success: function(data) {
    var received = true;
    if(received) {
        if(data < 2) {
            do_something
        } else {
            do_something
        }
    } else {
        do_something else
    }
}

How can I send 2 variable on echo json_encode($count); in order to do a double check for "is ID in the array? Is the array less than 2?" or is it there another way I'm missing?

8
  • 1
    what i can suggest you that use in_array() instead of foreach() to check ajax given values lies in your array or not Commented Mar 28, 2020 at 6:40
  • Just pass an array e.g. echo json_encode(array('found' => $found, 'count' => $count)); and you will get an object in your success code and you can access the values via data.found and data.count (note you need to specify dataType: json or parse the data) Commented Mar 28, 2020 at 6:40
  • @Nick yes exactly what I was trying to do but not fond of PHP, so that's how we send 2 vars right? Commented Mar 28, 2020 at 6:41
  • @AnantSingh---AlivetoDie mind to post a solution answer based on that? Commented Mar 28, 2020 at 6:41
  • 1
    @rob.m sorry, wrote the comment in a hurry, it should have been dataType: "json". But I see you have a working solution now anyway. Commented Mar 28, 2020 at 7:23

1 Answer 1

1

the simple way to do is use in_array() along with array output:

$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);

if(in_array($post_id,$userPostsInt)){
    echo json_encode(array('found'=>'yes','count'=>$count)); 
}else{
    $totSaved[] = $post_id;//add new value for next time checks
    echo json_encode(array('found'=>'no','count'=>$count)); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

bingo! Thanks 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.