Link to home
Start Free TrialLog in
Avatar of Vipin Kumar
Vipin KumarFlag for India

asked on

Split an array into multiple arrays

Hi,

I have below an array I want to split in three separate arrays. One array contains the username, second array contains Firstname and the thrid array contains Lastname.

 How can I achieve that?

Array ( [0] => Array ( [username] => admin [firstname] => Portal [lastname] => Administrator ) [1] => Array ( [username] => vipin [firstname] => Vipin [lastname] => Kumar ) )

Open in new window


Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of Brian Tao
Brian Tao
Flag of Taiwan, Province of China 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
Try this
/* Your array */
$arr = array(
  array(
    "username"=>"admin",
    "firstname"=>"Portal",
    "lastname"=>"Administrator"),
  array(
    "username"=>"vipin",
    "firstname"=>"Vipin",
    "lastname"=>"Kumar"));

/* New arrays */
$usernames = array();
$firstnames = array();
$lastnames = array();
foreach($arr as $user){  
  $usernames[] = $user["username"];
  $firstnames[] = $user["firstname"];
  $lastnames[] = $user["lastname"];
}

Open in new window

Or with this code for (somewhat) better performance:
$usernameArray = array();
$firstnameArray = array();
$lastnameArray = array();

// assume that your current array is named $currentArray
for ($i = 0, $j = count($currentArray); $i < $j; $i++){
  $usernameArray[] = $currentArray[$i]["username"];
  $firstnameArray[] = $currentArray[$i]["firstname"];
  $lastnameArray[] = $currentArray[$i]["lastname"];
}
// now you have them in separate array

Open in new window