Manipulate non-existent variables in the array

-1

How to mount the following array if one of the variables is not defined?

$a = 1; $b = 2; $d = 4; $array = array($a, $b, $c, $d);

The values of the variables ($ a, $ b, $ c, and $ d) come from a server and often do not contain any value, so the array becomes inconsistent.

As a workaround, I could use isset () to check if they exist and if they did not exist, assign any value. But, I can not assign new values if they do not exist. How to proceed in the assembly?

If one of these does not exist, it is returned, as in the example code where the variable $ c: Undefined variable: c is missing

    
asked by anonymous 18.04.2014 / 00:46

2 answers

8
$array = array();

if(isset($a))
    $array[] = $a;

if(isset($b))
    $array[] = $b;

// . . .

In the above way, only the variables that exist will be added to the array.

    
18.04.2014 / 00:57
1

Our @Cahe friend's answer is a great solution. But I'd like to share here another alternative that, perhaps, might make the code a bit more simplified.

It is the function compact ()

According to the PHP Manual:

  

For each of the parameters passed, compact () looks for a variable   with the name specified in the symbol table and adds it to the   output so that the variable name will be the key and its contents   will be the value for this key.

     

... Any string with a variable name that does not exist will be   simply ignored.

That's exactly what you need, in a simplified way.

See an example:

<?php

    $a = 1;
    $b = 2;
    $d = 3;

    $array = compact('a', 'b', 'c', 'd');

    print_r($array); // Array ( [a] => 1 [b] => 2 [d] => 3 )
    
11.07.2014 / 18:31