1

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.

2
  • Use array_filter($array); or use if conditions. Or make your array using if conditions and $array[] = $name; etc...not sure you need to create a string just to explode() it to an array when you can just make an array. Commented Oct 20, 2015 at 21:57
  • See @DontPanic for an example. Commented Oct 20, 2015 at 22:01

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

6 Comments

i try your code, and i change $color="" and $born_date=""
this born_date always show, so i must create else if again ?
Do you mean that each of the elements should only be included in the array if they are not null and != ""?
yes. if $born_date="" / $color="" / $name="" / address="" this resut array not show
if $born_date and $color null > Array ( [0] => John [1] => Moscow )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.