0

I have an array that is filled with values dynamically and I have to check if a value exists.

I tried the follwing but it's not working:

while (.....) {
    $fileData[] = array( "sku" => $sku, "qty" => $qty);
}

$product_sku = $product->getSku();

if (in_array(array("sku",$product_sku), $fileData)){
    echo "OK <BR/>";    
}
else{
    echo "NOT FOUND <BR/>"; 
}

The whole thing with keys confuses me. Should I change the table structure or just the in_array() statement? Can you help me find a solution?

hakre
  • 193,403
  • 52
  • 435
  • 836
zekia
  • 4,527
  • 6
  • 38
  • 47
  • possible duplicate of [php: access array value on the fly](http://stackoverflow.com/questions/13109/php-access-array-value-on-the-fly) – OZ_ Sep 14 '11 at 14:00
  • I really don't understand what my question has to do with the one you posted. – zekia Sep 14 '11 at 14:04
  • Oh, ok, I think you explained it somewhat confusingly, but you're looking to see if the value returned by getSku exists in *any* of the fileData arrays? – typeoneerror Sep 14 '11 at 14:17
  • yes that's it. Sorry for the misleading question, I'm really confused with php arrays too:) – zekia Sep 14 '11 at 14:20

1 Answers1

1

You can see if a key exists in an array with:

array_key_exists('sku', $fileData);

also, you can just check it directly:

if (isset($fileData['sku'])

It looks like you might be trying to recursively check for a key though? I think we'd need to see what getSku() returns. $fileData[] appends a value to an existing array so if $fileData was an empty array you'd have

fileData[0] = array("sku" => $sku, "qty" => $qty);

not

fileData = array("sku" => $sku, "qty" => $qty);

Try this on for size (with some fake data for demo purposes):

$fileData = array(
    array("sku" => "sku1", "qty" => 1),
    array("sku" => "sku2", "qty" => 2),
);

$sku = "sku2"; // here's the sku we want to find
$skuExists = false;

// loop through file datas
foreach ($fileData as $data)
{
    // data is set to each array in fileData
    // check if sku exists in that array
    if (in_array($sku, $data))
    {
        // if it does, exit the loop and flag
        $skuExists = true;
        break;
    }
}

if ($skuExists)
{
    // do something
}
typeoneerror
  • 55,990
  • 32
  • 132
  • 223
  • the fileData[]... code is inside a loop. I'll edit the question's code, in order to make that clearer. Also getSku() returns a code like "w125-256" – zekia Sep 14 '11 at 14:06
  • I think that I may have completely misunderstood the keys in php arrays. I'm quite new to php – zekia Sep 14 '11 at 14:16