Assign a variable only if another variable is set - an elegant way

try
    {
        $contactoCriado = $comandos->createContact($contactoVo);
    }
    catch(EppCommandsExceptions $e)
    {
        $erros .= ' ##Erro Contacto - Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
    }

    $nicHandleTitular = $contactoCriado['id'];

Here $contactoCriado could or couldn’t be set.
So we can:


if (isset($contactoCriado)) 
{
 $nicHandleTitular = $contactoCriado['id'];
} 

Isn’t there a shorter way?

isset($contactoCriado) ? $nicHandleTitular = $contactoCriado['id'];

Newbie trying to behave like a pro,
Márcio

Yes. And I use it a lot. But it wasn’t there before. Probably some maintenance stuff was going on.

:wink:

btw, (after I posted, and the page was refreshed, I got the + :slight_smile: )

Multi-quote?
That’s the ‘+’ button next to the ‘quote’ button :slight_smile:


isset($contactoCriado) and $nicHandleTitular = $contactoCriado['id']; 

It’s the shortest way to do it but I don’t recommend it as it’s not as readable as an if statement or a ternary operator (a ? b : c);

Off Topic:

Can’t believe I just ended a sentence with a semicolon. Too much time spent coding :wink:

Where is the multi quote? :s
hm! No good!

Thank you both.

Thanks immerse for helping me writing better, and thanks Anthony for helping me thinking better. :smiley:

K. Regards,
Márcio


$nicHandleTitular = isset($contactoCriado) ? $contactoCriado['id'] : null ;

This will set $nicHandleTitular to the id if $contactoCriado is set, or set it to null if it isn’t.
You could then check the $nicHandleTitular using is_null later.


<?php
try{
  $contactoCriado = $comandos->createContact($contactoVo);
  $nicHandleTitular = $contactoCriado['id'];
}catch(EppCommandsExceptions $e){
  $erros .= ' ##Erro Contacto - Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
?>