Joe Scotto Joe Scotto - 2 months ago 8
PHP Question

Prepend all array elements before a certain index in foreach loop

I'm trying to create a function that will format the paths for my breadcrumbs. I have a basic idea of what I want to do but not sure how to implement it. I want to prepend everything in the array before a certain index inside of a loop and do it for every element of that array. I currently have the following code but the issue is that

$breadcrumbs[0]
is being defined by me, I need it to be automatically defined inside of PHP.

public static function formatBreadcrumbs ($path) {
// Explode path into an array
$breadcrumbs = explode('/', $path);

$counter = 0;

foreach ($breadcrumbs as $breadcrumb) {
if ($breadcrumb !== $breadcrumbs[0]) {
$formattedBreadcrumbs[] = $breadcrumbs[0] . '/' . $breadcrumb;
}
}

var_dump($formattedBreadcrumbs);
}


For example if I input an array such as:

$path = array(
'documents',
'text',
'work'
);


I would want my function to output:

$formattedPath = array(
'documents',
'documents/text',
'documents/text/work'
);


In theory, this seems pretty simple but the logic behind it is boggling my mind a bit. Any help would be great, Thanks!

Answer
$path = array(
    'documents',
    'text',
    'work'
);

$cur_path = '';
$new_array = array();
$count = 0;
foreach($path as $path_item)
{
    if($count == 0)
    {
        $cur_path = $path_item;
    }
    else
    {
        $cur_path .= '/' . $path_item;
    }

    $new_array[] = $cur_path;
    $count++;
}

Tested. $new_array should equal:

Array ( [0] => documents [1] => documents/text [2] => documents/text/work )
Comments