Array_search does not work

Asked

Viewed 49 times

-3

Does not locate the Array key number. Page code:

 $cnpj = "000000000000000";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"http://xxxxxxxxxx.xxxxx/".$cnpj);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
$data = utf8_encode(curl_exec($ch));
$texto = explode("<td>",$data);

$chave = array_search('Natureza Jurídica',$texto);

echo $chave;
print_r ($texto);

Array code:

(
    [0] => 
    [1] => CNPJ
    [2] => xxxxxxxxxxxx [ MATRIZ ]
    [3] => Nome da empresa
    [4] => xxxxxxxxxxxxxxxxxx
    [5] => Fantasia nome
    [6] => xxxxxxxxxxx
    [7] => Inicio atividade data
    [8] => xxxxx
    [9] => Natureza jurídica
    [10] => xxxxxxxxxxxxxx
)

I tried to do with Array_search to return the number of the Array that is the name, but does not return. I tried if and Else command but also does not return anything, as if the variable is empty.

1 answer

2

If you are trying to pick up the array index at the "Legal Nature" string position, note that array_search() is case-sensitive. Vide PHP manual:

If Needle for a string, the comparison is done in a way that differentiates uppercase and lowercase.

In the array, the value that should be returned is:

[9] => Natureza jurídica

However, here you are searching with the capital "J":

$chave = array_search('Natureza Jurídica',$texto);

What makes that array_search() return false.

Try to change the search string so that it matches faithfully the value contained in the array:

$chave = array_search('Natureza jurídica',$texto);
  • I settled the whole case-by-case thing and it didn’t work out the same way.

  • 1

    +1. Correcting Case, array_search works perfectly with the Array provided in the question: https://ideone.com/2rHzWY

Browser other questions tagged

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