0

I am building breadcrumbs and I would like to do it from all segments from the current url. I am getting the array that looks like this

$segments = [0 =>'users',
             1 =>'index',
             2 =>'all'];

I'd like to combine the array in this way :

$routes = [ 0 =>'users',
            1 =>'users/index',
            2 =>'users/index/all'];

I have tried using array_map

            $segs = array_map(function($a){return $a."/".$a;},$segments);

but it combines the same array item twice

Any help is appreciated.

1
  • Create a loop that goes over the array, concats the current string and adds the value to a new array. Commented Jul 3, 2015 at 9:49

4 Answers 4

4

This should work for you:

Just loop through each element and take an array_slice() from the start until the current element, which you then simply can implode() with a slash.

<?php

    $segments = ["users", "index", "all"];

    foreach($segments as $k => $v)
        $result[] = implode("/", array_slice($segments, 0, ($k+1)));

    print_r($result);

?>

output:

Array
(
    [0] => users
    [1] => users/index
    [2] => users/index/all
)
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to do it using array_map() same as @Rizier123's method,

$segments = ['users','index','all'];

$routes = array_map(function($v, $k) use ($segments){
            return implode('/', array_slice($segments, 0, ($k+1)));
        }, $segments, array_keys($segments));

1 Comment

You may also want to initialize $till_now
0

Use this code to fix this issue :

$arr = array(0 =>'users', 1 =>'index', 2 =>'all');
print_r(returnPath($arr));

function returnPath($urlArr = null){
    $index = 1; $sep='';
    $length = count($urlArr);
    foreach($urlArr as $key => $item){   
        if($index > 1 && $index < $length){ $sep = '/'; }

        $temp .= $sep.$item; 
        $urlArr[$key] = $temp; 

    $index++;
    }

    return $urlArr;
}

Comments

0

To avoid slicing and imploding on every iteration, you can concatenate and ltrim instead.

Code: (Demo)

$segments = ["users", "index", "all"];

var_export(
    array_map(
        function($v) {
            static $path = '';
            return ltrim($path .= "/$v", '/');
        },
        $segments
    )
);

Output:

array (
  0 => 'users',
  1 => 'users/index',
  2 => 'users/index/all',
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.