make an Array from 2 Arrays

122
July 06, 2018, at 07:20 AM

I have this:

$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe@email.com";

Using a foreach, I need the final array format to look like:

$mergedArrays = array(
    'FirstName'        =>"John",
    'LastName'     => "Doe",
    'Email'       =>'johndoe@email.com',
);
print_r($mergedArrays);
Answer 1

If you are sure that both array will contain the same number separeted by comma, use this:

Version 1 (testing with 100000 takes ~0.08s, +-4x faster)

<?php
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe@email.com";
$Array1 = explode(',', preg_replace('/\s*,\s*/',',',$Array1)); //remove spaces before and after comma
$Array2 = explode(',', preg_replace('/\s*,\s*/',',',$Array2));
if(count($Array1) == count($Array2)) {
    $result = array_combine($Array1, $Array2);
}
print_r($result);

Output:

Array (
    [FirstName] => John
    [LastName] => Doe
    [Email] => johndoe@email.com
)

Alternative version from @castis (testing with 100000 takes ~0.3s)

$Array1 = explode(',',$Array1);
$Array2 = explode(',',$Array2);
$result = array_combine(array_map('trim', $Array1), array_map('trim', $Array2));
Answer 2

If you must use a foreach (where array_combine would do):

<?php
$columns = ['FirstName', 'LastName', 'Email'];
$data    = ['John', 'Doe', 'johndoe@email.com'];
foreach($columns as $k => $v)
    $result[$v] = $data[$k];
var_export($result);

Output:

array (
    'FirstName' => 'John',
    'LastName' => 'Doe',
    'Email' => 'johndoe@email.com',
)
READ ALSO
Verify password - Login system PHP

Verify password - Login system PHP

I'm working on a login and register system for a website, however the system has to be very secure and fast but, I don't know if I'm on the right way or notI finished the project but, I think it might be slow when 1000+ users login at the same time

119
What characters should I block in a contact form (for security purpose)?

What characters should I block in a contact form (for security purpose)?

I am building a contact form script that will work for all types of simple contact forms without having to define the inputs in the PHP file

154
php api binding parameter getting error

php api binding parameter getting error

I'm a beginner coder and trying to create a simple php API for my websiteAbove is the API code

98
Multiple template system with CodeIgnitor

Multiple template system with CodeIgnitor

I want to create a website which will have a default template and may have N number of templates in future which users buying the script may be able to choose from as per their own likes and needsHow to make such template system in CodeIgnitor? A reliable...

110