Search code examples
phparraysexplodestrposarray-intersect

PHP match comma separated string with array value but not in exact order


I have a possibly simple query but couldn't find an exact solution anywhere.

There is a comma separated string such as 1,3 and an array with values such as 1,3,2 OR 3,1,4. I need a function that when I try to search this string in the array, it returns TRUE for both the records as the number 1 & 3 exists in both array values but just in different order.

I have tried using array_search, strpos and even explode to first make the string in an array followed by array_intersect to intersect both arrays hoping to get a positive match but always only returns the array with values 1,3,2 and not 3,1,4.

Any suggestions or pointers would be extremely helpful.

Many thanks in advance.

======================

PS: Here's my code

        //Enter your code here, enjoy!
$st_array = array();
$st_data1['id'] = 1;
$st_data1['title'] = 'Jane doe';
$st_data1['disk'] = '1,3,2';
array_push($st_array, $st_data1);

$rc_disk_id = '1,3';

$st_data2['id'] = 2;
$st_data2['title'] = 'Jane Smith';
$st_data2['disk'] = '3,1,4';
array_push($st_array, $st_data2);


foreach($st_array as $st_data) {
    $rc_disk_ids = explode(",",$rc_disk_id);
    $match = array_intersect($rc_disk_ids, $st_data);
    if (!empty($match)) {
        echo "\nFound\n";
        print_r($st_data);
    }
    else {
        echo "Nope!";
    }
}

Solution

  • Your code is very close. You need to also explode the list of disk ids in $st_data, and then use array_diff to check whether all of the values in $rc_disk_ids are present in that list:

    foreach($st_array as $st_data) {
        $rc_disk_ids = explode(",",$rc_disk_id);
        $st_disk_ids = explode(',', $st_data['disk']);
        $match = array_diff($rc_disk_ids, $st_disk_ids);
        if (empty($match)) {
            echo "\nFound\n";
            print_r($st_data);
        }
        else {
            echo "Nope!";
        }
    }
    

    Output for your sample data:

    Found
    Array
    (
        [id] => 1
        [title] => Jane doe
        [disk] => 1,3,2
    )
    
    Found
    Array
    (
        [id] => 2
        [title] => Jane Smith
        [disk] => 3,1,4
    )
    

    Demo on 3v4l.org