This is more of a conceptual question concerning the built in functionality of PHP and arrays. I was wondering if there is any way to do the following:
You have an array $a
and this array contains 5 elements (0-4) for the purpose of this example.
Is there any way to make a new array, which would contain the following:
$b[0] = $a[0];
$b[1] = $a[0] + $a[1];
$b[2] = $a[0] + $a[1] + $a[2];
$b[3] = $a[0] + $a[1] + $a[2] + $a[3];
$b[4] = $a[0] + $a[1] + $a[2] + $a[3] + $a[4];
etc..
I imagine an example of it's use would be bread crumbs on a website, where you could click on any directory of a given link like /dir1/dir2/dir3/dir4
Is there anything built into PHP that can handle building up an array in this fashion? Or examples of a function which handles this? Or even a better way to go about this.
Thanks!
EDIT: Here is the final solution via the help of you guys! This will build the link, and create the proper link for each directory/element.
//$a is our array
$max = count($a);
foreach (range(1,$max) as $count) {
$b[] = implode("/", array_slice($a, 0, $count));
}
foreach($b as $c) {
$x = explode('/' , $c);
$y = array_pop($x);
echo "<a href='$c'>".$y."</a>"."/";
}
An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
If you just want the five combinations as in your example then:
foreach (range(1,5) as $count) {
$b[] = implode("/", array_slice($a, 0, $count));
}
You'd be best with a recursive function in that case.
$arr = array('dir1', 'dir2', 'dir3', 'dir4', 'dir5');
function breadcrumbs($a)
{
// Remove first value
$first = array_shift($a);
// Loop through other values
foreach ($a as $key => $value)
{
// Add first to remaining values
$a[$key] = $first . '/' . $value;
}
// Return array
return array($first) + breadcrumbs($a);
}
Untested, but should work. It will make each sequential value contain the values before it in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With