Handle missing variables in array

Asked

Viewed 123 times

-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 solution, I could use isset() to check if they exist and if they do not exist, assign any value. But, I cannot assign new values if they do not exist. How to proceed in the mount?

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

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 in the array.

  • Cahe, thank you.

  • I’m sorry, I didn’t see that there was a double question...

1

Our friend @Cahe’s answer is a great solution. But I would like to share here another alternative that, perhaps, can make the code a little more simplified.

Is the function Compact()

According to the PHP Handbook:

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

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

It’s exactly what you need, in a more simplified way.

Take 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 )

Browser other questions tagged

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