PHP in_array()

Asked

Viewed 223 times

4

My array $tx is:

Array
(
    [tax_val] => Air bag
)

testing:

echo (in_array('Air bag',$tx['tax_val'])?'Existe':'Não existe');

Returns:

Warning: in_array() expects Parameter 2 to be array, string Given in .....

I tested if it is array, cut ARRAY:

if(is_array($tx)) {
    echo '<p>ARRAY</p>';
} else {
    echo "<p>NAO ARRAY</p>";
}

Changing the code to:

echo (is_array($tx) && in_array('Air bag',$tx['tax_val'])?'Existe':'Não existe');

Returns nothing.

I need it to be ternary, but it doesn’t work, which is wrong if it has two values in the in_array()?

1 answer

6


This is happening because you’re doing the check with a string.

//in_array('Air bag',$tx['tax_val'])
// é isso que o php está vendo
in_array('Air bag', 'Air bag' );
//                      ^
// ou seja $tx['tax_val'] não é um array

Maybe what you’re after is something like:

$tx = [ "tax_val" => "Air bag" , "outra_key" => "outro_valor" ];

$valores = array_values( $tx );
/// nesse momento $valores  == [ 'Air bag', 'outro_valor' ];

echo "Existe na array: ";
echo in_array('Air bag', $valores ) ? "Sim" : "Não";

echo "\nQual é a Key => ";
echo array_search( 'Air bag' , $tx );

echo "\n";

Example of implementation

  • 1

    Thanks for the help, it was of great value!

Browser other questions tagged

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