How to pull the values of an input if it has a certain value - PHP

Asked

Viewed 25 times

0

So, I’m entering data into SQL and need to pull the address the client left as the main one. How do I pull the values of the index where the [main] is equal to 1?

It must be something simple but I couldn’t figure it out.

[teste] => Array
        (
            [0] => stdClass Object
                (
                    [pais] => Brasil
                    [principal] => 1
                )

            [1] => stdClass Object
                (
                    [pais] => Brasil
                    [principal] => 0
                )
        )

1 answer

1


I’m going to assume you want the indices where those values are to then access those same values, in which case you’ll be taking an unnecessary turn

You can obtain your own values by using array_filter:

$filt = array_filter($test, function($v) {
    return $v->principal === 1; 
});
// $filt = array_values($filt); // executar isto apenas se quiseres fazer reset às chaves
print_r($filt); // aqui veras os resultados

DEMONSTRATION

If you really want the indices:

$keys = [];
foreach($test as $k => $v) {
    if($v->principal === 1)
        $keys[] = $k;
}
print_r($keys); // aqui veras os resultados

DEMONSTRATION

  • Thanks for the info!

Browser other questions tagged

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