Reputation: 1196
Hello I want create string to array. I have 4 variables:
<?php
$name = "John";
$address = "Moscow";
$born_date = "13-11-1995";
$color = "red";
$join = $name.":".$address.":".$born_date.":".$color;
$array = explode(':', $join);
print_r ($array);
?>
This array result is:
Array ( [0] => John [1] => Moscow [2] => 1995-11-13 [3] => red )
When I change $color
variable to null
like $color="";
This result like this:
Array ( [0] => John [1] => Moscow [2] => 1995-11-13 [3] => )
I want array
number 3 not to show. I want if all $variable == NULL
/ $variable=="undefined"
/ $varable=""
Show like this:
Array ( [0] => John [1] => Moscow [2] => 1995-11-13)
The array shows only variable filled.
Upvotes: 1
Views: 41
Reputation: 41810
I'm not sure what your requirements are, but it seems strange to create this array by joining the variables together and then exploding them. You could just add them directly to the array, and add the color conditionally:
$array = array($name, $address, $born_date);
if ($color) {
$array[] = $color;
}
If you need all of the elements to be added conditionally, you can create an array containing all of them and then use array_filter as Rasclatt suggested to eliminate the empty ones.
$array = array($name, $address, $born_date, $color);
$array = array_filter($array);
If it is important that the keys remain sequential, you can use
$array = array_values(array_filter($array));
Upvotes: 1