How do i check if two values exist in a multidimensional array?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How do i check if two values exist in a multidimensional array? on this date .

I am working on a poll system where each user can vote once per poll. If they submit their vote it will be inserted in the polls_results table

To check if a user already submitted a vote i made an sql query that selects * from the table polls_results and puts the result in a array:

$query = 'SELECT * FROM polls_results';
$result = mysqli_query( $db, $query );
$array = array();
    
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
    array_push( $array, $row );
}

This is the output of the array with my current table data.

Array
(
        [0] => Array
            (
                [result_id] => 132
                [poll_id] => 16
                [user_id] => 2
                [vote] => 0
            )
    
        [1] => Array
            (
                [result_id] => 133
                [poll_id] => 17
                [user_id] => 2
                [vote] => 0
            )
    
        [2] => Array
            (
                [result_id] => 131
                [poll_id] => 16
                [user_id] => 1
                [vote] => 1
            )
    
)

My question is how do i check if a submitted vote exists in my multidimensional array?

I already tried it with two array_search functions in a if-statement but then it only checks if a user_id and poll_id exist in the array. But i want it to check if there’s an item with those two combined.

Answer

To check if a user already voted you can also use SQL instead of the checking inside PHP, I suppose.

So maybe checking the user_id, poll_id and vote like this:

$userId = 1;
$pollId = 2;

$query = "SELECT * FROM `polls_results` WHERE `user_id`={$userId} AND `poll_id`={$pollId} AND `vote`=NULL";

would be better approach. If there is a result returned then the user does not have voted.

If 0=no and 1=yes, then I would suggest using NULL as default value for the vote column. So if the vote column is NULL, it means that the user did not vote at all. I updated my query to check for this.

Please be aware that you should sanitize $userId and $pollId so that no SQL-injection happens. You should check PHP prepared statements.