3

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
        )
2

4 Answers 4

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 );
Sign up to request clarification or add additional context in comments.

Comments

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';
    }
}

Comments

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';
}

Comments

0

You can use :

foreach($yourArray as $arrayItem){
    if (strpos($arrayItem['avs_id'], 'a_b_c') !== false) {
        //return true : code here
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.