How to insert a statement in the array only if it is true?

-2

I need to somehow check if there is any element within a given array and if it exists, put a string in a specific place. For example:

  

I need to check if $categoria is not empty

$categoria = array($values);
  

And after checking that it is not empty, insert the string below into filter

$categoria = " 'Categoria' => array($values) ";

The array is this and I have to insert these instructions inside the filter:

$dados = array (
    'fields' => array(
        'ImoCodigo', 
        'Categoria', 
        'Bairro',
        'ValorVenda', 
        'Dormitorios', 
        'Vagas', 
        'FotoDestaque'
    ),
    'filter' => array(
        // As strings devem ser inseridas exatamente aqui separadas por vírgula
    ),
    'paginacao' => array(
        'pagina' => 1,
        'quantidade' => 50
    )   
);
  

The end result would look like this:

...
'filter' => array(
    'Categoria' => array($values),
    'Cidade' => array($cidades),
    'ValorVenda' => array($preco)
),
...
    
asked by anonymous 02.01.2016 / 18:29

1 answer

2

Checks if the value is not empty. If it is empty, use the arrow as null.

Example of how to add filter to array $dados :

'filter' => array(
    'categoria' => ((!empty($values))? array($values) : null)
),

But it seems odd to assign $ values as an array array($values) . Is that right? You'll just be creating unnecessary memory space.

If you do not want the index categoria when empty, do the following logic:

Create the array $dados normally, but without the index "filter"

$dados = array (
 ....
);

With the array created, simply add or remove the indexes as you want:

((!empty($values))? $dados['filter']['categoria'] = array($values) : '');

Full example:

$dados = array (
    'fields' => array(
        'ImoCodigo', 
        'Categoria', 
        'Bairro',
        'ValorVenda', 
        'Dormitorios', 
        'Vagas', 
        'FotoDestaque'
    ),
    'paginacao' => array(
        'pagina' => 1,
        'quantidade' => 50
    )   
);
((!empty($values))? $dados['filter']['categoria'] = array($values) : '');
    
02.01.2016 / 18:39