Check string is contained in PHP Array

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

    
asked by anonymous 12.08.2017 / 23:59

2 answers

3

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

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

Try this.

This will only work if the data value is the same as the searched. Considering that one of the data is Alguma Coisa : searching for Alguma Coisa will work, if searched by Alguma will not be found.

    
13.08.2017 / 01:20
2

You need to use count() to know the size of the array (ie: the loop limit ), and then $content[$i][$i] to go looking for the correct 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'; 
}
    
13.08.2017 / 00:02