Check string is contained in PHP Array

Asked

Viewed 545 times

3

I have a function in Curl, its return is an indefinite amount of data, but, its format is standard.

Return:

    array(86) {
      [0]=>
      array(2) {
        ["value"]=>
        int(1)
        ["data"]=>
        string(27) "retorno 1"
      }
      [1]=>
      array(2) {
        ["value"]=>
        int(2)
        ["data"]=>
        string(13) "retorno 2"
      }
      [2]=>
      array(2) {
        ["value"]=>
        int(3)
        ["data"]=>
        string(87) "retorno 3"
      }
      [3]=>
      array(2) {
        ["value"]=>
        int(4)
        ["data"]=>
        string(33) "retorno 4"
      }
      [4]=>
      array(2) {
        ["value"]=>
        int(5)
        ["data"]=>
        string(28) "retorno 5"
      }
    }

I need to check if a variable is contained in the value string and get the sequence array number.

I tried this way:

    $content = curl_exec($ch);
    $var= 'minha_variavel';
    for ($i = 0; $i < $content; $i++)
    {
        $element = $content->string($i);
        if (preg_match("#{$var}#i", $element))
        {
            return 'OK achei';
        }
    }

Unsuccessful

2 answers

4

If "contained" which means "identical" you can use the array_search:

$index = array_search('Procurado', array_column($array, 'data'), true);

Test this.

This will only work if the value of data is the same as the searched. Considered as one of the data be it Alguma Coisa: search for Alguma Coisa will work if searched by Alguma will not be found.

2

You have to use count() to know the size of the array (ie: loop limit), and then $content[$i][$i] to get the right index/element:

$content = curl_exec($ch);
$var = 'minha_variavel';
for ($i = 0; $i < count($content); $i++){
    if ($content[$i].data == $var) return 'OK achei';
    // ou no caso de procurares uma parte somente:
    if (strpos($content[$i].data, $var) !== false) return 'OK achei'; 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.