user1437251
user1437251

Reputation: 309

foreach concatenate each element to next one

I would like to concatenate each element of array to next one. I want the output array to be:

Array
(
[0] => test
[1] => test/test2
[2] => test/test2/test3
[3] => test/test2/test3/test4
)

I tried the following way which concatenates each string to itself:

$url = preg_split("/[\s\/]+/", "test/test2/test3/test4");
foreach ($url as $dir) {
   $dir .= $dir;
} 

Any help appreciated.

Upvotes: 0

Views: 65

Answers (4)

AbraCadaver
AbraCadaver

Reputation: 78994

Here's a quick way. For simple splitting just use explode():

$url  = explode("/", "test/test2/test3/test4");

foreach($url as $value) {
    $temp[]   = $value;
    $result[] = implode("/", $temp);
}

Each time through the loop, add the current value to a temporary array and implode it into the next element of the result.

Upvotes: 0

Parth  Mahida
Parth Mahida

Reputation: 614

$url = preg_split("/[\s\/]+/", "test/test2/test3/test4");
$arr = array();
$str = '';
foreach ($url as $key => $dir) {

    if ($key !== 0) {
        $str .= '/' . $dir;
    } else {
        $str .= $dir;
    }

    $arr[] = $str;
}

On each iteration concate a string with new value and add it as a separate value for your output array.

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133380

You should obtain the result you need in $my_array

$url = explode("/", "test/test2/test3/test4");

$str ='';
foreach($url as $key => $value){
  if ( $str == '') {
     $str .= $str;
  } else {
    $str .= '/'.$str;
  }
  $my_array[$key] = $str ;
  echo $str . '<br />';

}

var_dump($my_array);

Upvotes: 1

Blinkydamo
Blinkydamo

Reputation: 1584

Maybe another way

<?php
$data = array( 'test', 'test2', 'test3', 'test4' );
for( $i = 0; $i < count( $data ); $i++ )
{
  if( $i != 0 )
  {
    $new[ $i ] = $new[ $i - 1 ] .'/'. $data[ $i ];
  }
  else
  {
    $new[ $i ] = $data[ $i ];
  }
}

var_dump( $new );

Output

array(4) {
  [0]=>
  string(4) "test"
  [1]=>
  string(10) "test/test2"
  [2]=>
  string(16) "test/test2/test3"
  [3]=>
  string(22) "test/test2/test3/test4"
}

Upvotes: 1

Related Questions