Jump to content

[SOLVED] Add to Array IF !=''


xProteuSx

Recommended Posts

How do I add a variable to an array only if the variable is not null.

 

I have a scenario in which I have a few variables -- lets say 4.  $_1, $_2, $_3, and $_4.  I want to add them to an array, but only if they are not null.

 

So if they all have a value the array would be:

 

$myarray = array($_1,$_2,$_3,$_4);

 

But if the value for $_2==''

 

$myarray = array($_1,$_3,$_4);

 

And if the value of $_2=='' and $_3==''

 

$myarray = array($_1,$_4);

 

What's the best way to do this?

Link to comment
Share on other sites

Here's one way:

<?php
$ary = array(); // create an empty array
if ($_1 != '') $ary[] = $_1;
if ($_2 != '') $ary[] = $_2;
if ($_3 != '') $ary[] = $_3;
if ($_4 != '') $ary[] = $_4;
?>

 

Another way would be to use variable variables:

<?php
$ary = array();
for ($i=1;$i<5;$i++)
   if (${'_'.$i} != '') $ary[] = ${'_'.$i};
echo '<pre>' . print_r($ary,true) . '</pre>';
?>

 

Ken

Link to comment
Share on other sites

When I use the following code:

 

<?php

$ary = array(); // create an empty array

if ($_1 != '') $ary[] = $_1;

if ($_2 != '') $ary[] = $_2;

if ($_3 != '') $ary[] = $_3;

if ($_4 != '') $ary[] = $_4;

?>

 

and then I try this:

 

echo $ary;

 

The output is simply: 'Array'

 

Is the code not written correctly, or do I have to output is using the explode function?

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.