0

I have two arrays:

array(1,2,3,4,5)
array(10,9,8,7,6)

Final array Needed:

array(0=>1:10,1=>2:9,2=>3:8,3=>4:7,4=>5:6)

I can write a custom function which would be quieck enough!! But i wanted to use a existing one so Is there already any function that does this in php? Pass the two input arrays and get the final array result? I read through the array functions but couldn't find any or combination of function that would provide me the result

2
  • The result should be 1:10 or 1,10? Commented May 29, 2013 at 10:37
  • Please see my edited final array. Thanks for all our valuable replys :) Commented May 29, 2013 at 11:07

5 Answers 5

4

No built in function but really there is nothing wrong with loop .. Just keep it simple

$c = array();
for($i = 0; $i < count($a); $i ++) {
    $c[] = sprintf("%d:%d", $a[$i], $b[$i]);
}

or use array_map

$c = array_map(function ($a,$b) {
    return sprintf("%d:%d", $a,$b);
}, $a, $b);

Live Demo

Sign up to request clarification or add additional context in comments.

1 Comment

O sorry I thought it was javascript since you're using inline functions (didn't knew that was possible in PHP!)
1

Try this :

$arr1   = array(1,2,3,4,5);
$arr2   = array(10,9,8,7,6);

$res    = array_map(null,$arr1,$arr2);
$result = array_map('implode', array_fill(0, count($res), ':'), $res);

echo "<pre>";
print_r($result);

output:

Array
(
    [0] => 1:10
    [1] => 2:9
    [2] => 3:8
    [3] => 4:7
    [4] => 5:6
)

1 Comment

+1 But you don't need array_fill ... implode would do just fine
0

See: http://php.net/functions

And especially: https://www.php.net/manual/en/function.array-combine.php

Also, I don't quite understand the final array result? Do you mean this:

array (1 = 10, 2 = 9, 3 = 8, 4 = 7, 5 = 6)

Because in that case you'll have to write a custom function which loops through the both arrays and combine item[x] from array 1 with item[x] from array 2.

Comments

0
<?php
  $arr1=array(1,2,3,4,5);
  $arr2=array(10,9,8,7,6);
  for($i=0;$i<count($arr1);$i++){
    $newarr[]=$arr1[$i].":".$arr2[$i];
 }
 print_r($newarr);
?>

Comments

0

Use array_combine

array_combine($array1, $array2)

http://www.php.net/manual/en/function.array-combine.php

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.