Chaya Cooper
Chaya Cooper

Reputation: 2530

in_array() keeps appending values if looping through db rows

I need to identify every instance where a value in one array (needle) occurs in another array (haystack). in_array() seems to be my best option, and the code below works perfectly until I need to use it on rows fetched from a db - it keeps appending values instead of setting them each time it's called.

While I can't actually use unset() in this situation, I was surprised to discover that even that didn't seem to resolve the problem.


UPDATE - Example of what's being returned

I temporarily changed the db values so that $needles has only value per row (in order to make it possible to sort through the values filling up my screen ;-))

  1. False;
  2. False; False; True;
  3. False; False; True; False; True;
  4. False; False; True; False; True; False; True;
  5. False; False; True; False; True; False; True; False;

This works correctly (I've posted a functional example here)

$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');

    foreach ($needles as $needle) {
        if (in_array($needle, $haystack) ) {
            $Match = 'True'; 
        }
        else {
            $Match = 'False'; 
        }
    }

This keeps appending values - Edited to reflect the code I'm using

$Customer_Categories_Arr = array('Casual','Trendy'); 

if ($stmt->columnCount()) {            
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {    
     $Product_Categories_Arr[]=$row["Taste_Category"];          
      // Use when column contains CSV
      // $Product_Categories_Arrx = explode(',', trim($Product_Categories_Arr[0]));          
      foreach ($Product_Categories_Arr as $Product_Category_Arr) {          
              if (in_array($Product_Category_Arr, $Customer_Categories_Arr)){   
                  $Matches_Product_Category = "True"; 
              } else {                                 
                  $Matches_Product_Category = "False";  
              }           
                  echo $Product_Category_Arr, ', ', $Matches_Product_Category, '; ';
        }   
   }
}

Upvotes: 1

Views: 247

Answers (3)

Malcolm Kindermans
Malcolm Kindermans

Reputation: 337

It is not really clear what you are trying to do. But maybe this would help:

$customerCategories = array('Casual', 'Trendy');
if( $stmt->columnCount() ){
    while( $row = $stmt->fetch( PDO::FETCH_ASSOC )){
        $productCategoryRow = $row[ 'Taste_Category' ];
        // If it is not working, try uncommenting the next line
        // $productCategories = [];
        $productCategories = explode( ',', trim( $productCategoryRow ));

        $match = "False";
        foreach( $productCategories as $productCategory ){
            if( in_array( $productCategory, $customerCategories )){
                $match = "True";
            }
            echo $match . ";";
        }
    }
}

This prints your result on the screen every time a loop is done. Is this what you mean?

Upvotes: 1

joram
joram

Reputation: 153

I am going to try an solve this. I think the problem is with:

$needles[]=$row["product_var"];

I think this should be:

$needles=$row["product_var"];

The column "product_var" contains an CSV (as you mentioned), so I can make an example like this:

$csv = "jake;john;alex;kim";

An example with brackets ($needles[]):

for($i=0; $i<5; $i++) {
    $needles[] = explode(";", $csv);
    echo(count($needles).", ");
}

returns:

1, 2, 3, 4, 5,

edit (for more explaining):

if I use print_r I see the array expanding, exactly how it happens in your example:

step 1: it adds an array to $needles with values ('jake','john','alex','kim')

step 2: it adds an array to $needles, so it contains 2x the values ('jake','john','alex','kim')

step 3: it adds an array to $needles, so it contains 3x the values ('jake','john','alex','kim')

etc.

Now without the brackets ($needles):

for($i=0; $i<5; $i++) {
    $needles = explode(";", $csv);
    echo(count($needles).", ");
}

This returns:

4, 4, 4, 4, 4,

And every time the array simply contains the values ('jake','john','alex','kim') -which is what you want.

Could this explain the "expanding values"? (or am I just doing something really stupid which has nothing to do with your problem??)

edit:

If this is what is going wrong, then you are adding to an array, instead of only using the new array from $row["product_var"] (hope this makes any sense; it seems I am pretty bad at explaining what's happening).

Upvotes: 0

v2solutions.com
v2solutions.com

Reputation: 1439

If you want the second block of code to do what the first block of code (which works correctly) does, then the second block should look like this -

if ($stmt->columnCount()) {
   while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {   
       $needle =$row["product_var"];              
       $Match = "False";  
        if (in_array($needle, $haystack)){   
            $Match = "True"; 
        }                  
    }
}

You don't need do use the foreach because that is replaced by the while loop in the second block.

Upvotes: 0

Related Questions