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?
Advertisement
Answer
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)); }