3

I'm trying to check if in an array there is any value of another array. The function array_key_exist() looks like what I'm searching for, but I don't understand how to give the key value at the function as an array. Here's the code:

$risultato_query_controllo_numero = mysql_query($query_controllo_numero);
$voucher_esistenti = array();

while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))) {
    $voucher_esistenti[] = $row['numero'];
}

Which populates the first array with numbers:

$voucher = range($numero, $numero + $quantita);

Which populates the second array with numbers.

What I need to do now is to check if any of the value in $voucher is present in $voucher_presenti.

1
  • The function you are looking for is array_intersect(). Both your arrays are indexed with sequential numbers starting from 0, their keys are not interesting. Commented Jun 22, 2016 at 12:15

3 Answers 3

4

You can use the array_intersect function:

$overlap = array_intersect($voucher, $voucher_presenti); 

You can find more examples in the documentation.

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

1 Comment

Didn't know that function. Nice and clean answer. :)
1

You could use the in_array() function to get the result you are looking for.

$arrayOne = range(1, 10);
$arrayTwo = range(5, 15);
foreach ($arrayOne as $value) {
    if (in_array($value, $arrayTwo)) {
        echo 'value '.$value.' is in the first and second array.<br />';
    }
}

Resources

Comments

1

in_array could be a good solution for your need, for example you can assign $voucher_esistenti only when you have a new value in the sql row.

$risultato_query_controllo_numero=mysql_query($query_controllo_numero);
$voucher_esistenti=array();
while(($row =  mysql_fetch_assoc($risultato_query_controllo_numero))){
    if(!in_array($row['numero'], $voucher_esistenti) {
         $voucher_esistenti[] = $row['numero'];
    }
} // this solution isn't optimal, because you will check subarrays with each new value

There's a better way to achieve that, by using a hashmap which has a complexity of O(1) ( best complexity :) )

$risultato_query_controllo_numero=mysql_query($query_controllo_numero);
$voucher_esistenti=array();
while(($row =  mysql_fetch_assoc($risultato_query_controllo_numero))){
// here is what we changed, instead of key = value, we actually append keys
    if(!isset($voucher_esistenti[$row['numero']]) {
        $voucher_esistenti[$row['numero']] = true;
    }
} 
/*
The second implementation is a lot faster due to the algorithm, but you will have to change the reading of $voucher_esistenti array. */

Comments

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.