Kevin Rave
Kevin Rave

Reputation: 14456

CSV search in CSV - php

I have an two variables as CSV strings. Example:

 $csva = "1,4,7,10,39,12";
 $csvb = "4,1,12";

I want to search if all elements in $csvb exist in $csva.

Is there a simple function to do this?

Note: I know we can loop through this to compare each element. But I am wondering if there is any php function to do this.

Any ideas?

Upvotes: 1

Views: 293

Answers (2)

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

Nope, the closest thing you can get is:

if(count(array_intersect(explode(',', $csva), explode(',', $csvb))) == count(explode(',', $csvb))){
    echo 'All items there';
}

Upvotes: 0

biziclop
biziclop

Reputation: 14616

http://codepad.org/nA2P6FCH

function csv_contains( $haystack, $needle ){
  return ! count( array_diff(
    explode(',',$needle ),
    explode(',',$haystack)
  ));
}

var_dump( csv_contains( "1,4,7,10,39,12", "4,1,12") ); //true

var_dump( csv_contains( "1,4,7,10,39,12", "4,1,12,999") ); // false

Upvotes: 2

Related Questions