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
https://forums.phpfreaks.com/topic/81450-solved-add-to-array-if/
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

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?

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.