2

I have an array of arrays as such below and I want to check if the [avs_id] contains a substring "a_b_c". How to do this in php?

  Array
            (
                [id] => 10003    
                [avs_id] => a_b_c_3248
            )

    Array
        (
            [id] => 10003    
            [avs_id] => d_e_f_3248
        )
coffeeak
  • 2,980
  • 7
  • 44
  • 87

4 Answers4

2

You can use array_filter():

$src = 'a_b_c';

$result = array_filter
(
    $array,
    function( $row ) use( $src )
    {
        return (strpos( $row['avs_id'], $src ) !== False);
    }
);     

3v4l.org demo

The result maintain original keys, so you can directly retrieve item(s) matching substring.

If you want only check if substring exists, or the number of items having substring, use this:

$totalMatches = count( $result );
fusion3k
  • 11,568
  • 4
  • 25
  • 47
0

Loop through your array and test for the string in the specific element of your array with strpos as in the example code below.

foreach($yourMainArray as $arrayItem){
    if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
        echo 'true';
    }
}
ThrowBackDewd
  • 1,737
  • 2
  • 13
  • 16
0

A loop may be more ideal but if you know what array index the string is in that you are after:

$arr = array('id'=>'10003', 'avs_id'=>'a_b_c_3248');

if (strpos($arr['avs_id'], 'a_b_c') !== false) {
    echo 'string is in avs_id';
}
Countach
  • 597
  • 1
  • 10
  • 20
0

You can use :

foreach($yourArray as $arrayItem){
    if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
        //return true : code here
    }
}
Alex
  • 3,646
  • 1
  • 28
  • 25