1

Here are my Inputs :

$firstname=array
("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");

$lastname=array
("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");

I need to create an array that will concatenate $firstname[i] with $lastname[$i}and thereby create an array that combines the first name and last name.

My output is below but it is not correct:

<?php
foreach($firstname as $first){
   foreach($lastname as $last){
  $fullname[]=$first." ".$last;
  }
}
print_r($fullname);
?>

I probably should not be using a foreach loop but I am stuck.

1
  • You need to use a loop; but not two loops Commented Mar 16, 2015 at 12:41

4 Answers 4

1

Assuming arrays of the same size:

$firstname=array("Raj","Swati","Kunal","Hema","Kareena","Deepika","Shilpa","Amitabh","Shahrukh","Kangana");    
$lastname=array("Kumar","Sharma","Kapoor","Malini","Kapoor","Padukone","Shetty","Amitabh","Shahrukh","Kangana");
$size = count($firstname);
for ($i=0; $i < $size; $i++) {
    $fullname[]=$firstname[$i]." ".$lastname[$i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

plain and simple. Love it !
1

This should work for you:

(Here I just loop through both arrays with array_map() and return them both concatenated into the $result array)

<?php

    $firstname = ["Raj", "Swati", "Kunal", "Hema", "Kareena", "Deepika", "Shilpa", "Amitabh", "Shahrukh", "Kangana"];
    $lastname = ["Kumar", "Sharma", "Kapoor", "Malini", "Kapoor", "Padukone", "Shetty", "Amitabh", "Shahrukh", "Kangana"];

    $result = array_map(function($v1, $v2){
        return "$v1 $v2";
    }, $firstname, $lastname);

    print_r($result);

?>

Output:

Array ( [0] => Raj Kumar [1] => Swati Sharma [2] => Kunal Kapoor [3] => Hema Malini [4] => Kareena Kapoor [5] => Deepika Padukone [6] => Shilpa Shetty [7] => Amitabh Amitabh [8] => Shahrukh Shahrukh [9] => Kangana Kangana )

2 Comments

is this an anonymous function youve used ?
@newbie Yes! The advantage with this method is when lets say you have 1 element more in $lastname your results array will just end with e.g. [x] => lastname so you don't have to worry if they are the same length
0

Provided you know the data in both arrays is in the correct order:

$out=[];
foreach($firstname as $key=>$val)
    $out[$key] = $val . ' ' . $lastname[$key];

var_dump($out);

Comments

0

One way would be to use array_combine;

$newArr = array_combine($firstname, $lastname);

foreach($newArr as $key => $value){
  echo $key." ".$value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.