xProteuSx Posted December 13, 2007 Share Posted December 13, 2007 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? Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted December 13, 2007 Share Posted December 13, 2007 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 Quote Link to comment Share on other sites More sharing options...
xProteuSx Posted December 13, 2007 Author Share Posted December 13, 2007 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? Quote Link to comment Share on other sites More sharing options...
rajivgonsalves Posted December 13, 2007 Share Posted December 13, 2007 you should try print_r($ary) instead of echo $ary; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.