Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

PHP: Pushing Array to Array

Using PHP, how can I push items to an array at the first level without going two levels deep?

$emails = array(); 

$contact_email = '1@example.com   ';
$contact_email_additional = '2@example.com, 3@example.com   ,    4@example.com';

array_push($emails, trim($contact_email));
array_push($emails, array_map('trim', explode(',', $contact_email_additional)));

echo '<pre>';
print_r($emails);
echo '</pre>';

Open in new window

The problem with the code above is that it puts an array inside an array, instead of adding the items to the array.
Array
(
    [0] => 1@example.com
    [1] => Array
        (
            [0] => 2@example.com
            [1] => 3@example.com
            [2] => 4@example.com
        )

)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sample code below. Working sample here
<?php
$emails = array(); 

$contact_email = '1@example.com   ';
$contact_email_additional = '2@example.com, 3@example.com   ,    4@example.com';

array_push($emails, trim($contact_email));
$emails = array_merge($emails, array_map('trim', explode(',', $contact_email_additional)));

echo '<pre>';
print_r($emails);
echo '</pre>';

Open in new window

All of the PHP array functions are documented in the online man pages.  It's worth taking a moment to read the descriptions (you can read them all in less than five minutes).  You'll be pleasantly surprised at how many array functions exist and how richly supportive they are!
http://php.net/manual/en/ref.array.php