mark rammmy
mark rammmy

Reputation: 1498

in_array with single and multidimension

I have two arrays a single dimension and multidim array ,the multidimension its comma

separated

$singledim =Array
(
    [0] => 333
    [1] => 673
    [2] => 434
    [3] => 67

)

$multidim = Array
(
    [0] => Array
        (
            [0] => 22
            [1] => 3336,673,34,342,432,23,323,434,765675765,7657567
        )

    [1] => Array
        (
            [0] => 24
            [1] => 2424,10
        )

    [2] => Array
        (
            [0] => 28
            [1] => 23,12,13,14,15,16
        )
............
}

I want to use in_array to check the single dimension array value exists .Belwo is the one i tried..

<?
foreach($multidim  as $multi)
{
  if(in_array($singledim,$multi[1])
  {

  }
  $i++;
}
?>

Upvotes: 0

Views: 112

Answers (3)

David Nguyen
David Nguyen

Reputation: 8528

foreach($multidim as $multi){
    foreach($singledim as $single){
        $temp_array = explode(',',$mutli[1]);
        if(in_array($single, $temp_array)){
            // do stuff
        }
    }
}

If you pass an array, that same array group must exist exactly in the same manner in the haystack in order to match.

Upvotes: 1

Aydin Hassan
Aydin Hassan

Reputation: 1475

$multi[1] is not an array. It is a comma separated string.

You can use explode to create an array from the string:

$vals = explode(',' ,$multi[1]);
if(in_array($singledim, $vals)
{

}

However, that will only work if $singledim is a string.

As noted in the comments, you are checking if a whole array is the same as the string in the second array. You could convert the first array to a string and then check they are equal:

$singleDimStr = implode(',' ,$singledim);
if($singleDimStr == $multi[1]) { 
}

Upvotes: 0

Marc B
Marc B

Reputation: 360612

You don't want in_array(). you want strpos(...) !== false. and note you WILL be subject to false positives. e.g. if you're searching for 1, then your 12, 21, etc... will false match. Your structure needs to be normalized, and each value individual value in the [1] sub-element should be its OWN array element.

Upvotes: 0

Related Questions