0

Let's say I have an array containing: apples, watermelons, grapes. What I'm trying to do is create another array with

apples, apples;watermelons, apples;watermelons;grapes

I tried using implode, but it's not exactly what I wanted. Is there a built in function for this task? Thanks!

EDIT: For clarification, the created string is basically a combination of these three elements. So the created array could also look like:

apples, apples-watermelons, apples-watermelons-grapes

3
  • it will be an array containing a string similar to that. it could be apples, apples-watermelons, apples-watermelons-grapes Commented Aug 9, 2012 at 3:00
  • Can you clarify what you are trying to do? Are you trying to make strings with random values picked from that array? Maybe you could provide a concrete example. Commented Aug 9, 2012 at 3:06
  • It is a concrete example, everything is picked in order :| Commented Aug 9, 2012 at 3:13

3 Answers 3

2

An elegant way to do it is with array_reduce

<?php
$my_array = array('apples','watermelons','grapes');

function collapse($result, $item) {
    $result[] = end($result) !== FALSE ? end($result) . ';' . $item : $item;
    return $result;
}

$collapsed = array_reduce($my_array, "collapse", array());
var_dump($collapsed);
?>

Testing:

matt@wraith:~/Dropbox/Public/StackOverflow$ php 11876147.php 
array(3) {
  [0]=>
  string(6) "apples"
  [1]=>
  string(18) "apples;watermelons"
  [2]=>
  string(25) "apples;watermelons;grapes"
}
Sign up to request clarification or add additional context in comments.

Comments

2
<?php
$my_array = array('apples','watermelons','grapes');
$string = '';
$result = array();
for ($i=0; $i<count($my_array); $i++) {
   $string .= $my_array[$i];
   $result[] = $string;
   $string .= '-';
}
print_r($result);

There may be a way to do it with array_walk() or array_map() or one of the other array_*() functions as well.

Comments

1
<?php

$array = array("apples", "watermelons", "grapes");
$newarray = $array;
for ($i = 1; $i < count($array); $i++)
{
   $newarray[$i] = $newarray[$i - 1] . ";" . $newarray[$i] ;
}

print_r($newarray);
?>

Output:

Array
(
    [0] => apples
    [1] => apples;watermelons
    [2] => apples;watermelons;grapes
)

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.