Jump to content

[SOLVED] Array variations


sphinx9999

Recommended Posts

Hi,

I'm trying to convert an array of text into all of its sequential variations keeping the elements in order, i.e. if the original array is:

$original=array('one','two','three','four');

I need to convert it into:

$new=array(
array('one'),
array('one','two'),
array('one','two','three'),
array('one','two','three','four'),
array('two'),
array('two','three'),
array('two','three','four'),
array('three'),
array('three','four'),
array('four')
);

Any ideas how this can be done (for a dynamic number of elements in the original array)?

Cheers

Link to comment
https://forums.phpfreaks.com/topic/78213-solved-array-variations/
Share on other sites

<?php

$original=array('one','two','three','four');

echo "<pre>"; print_r(get_sequence($original)); echo "</pre>";

function get_sequence($array)
{
$size = count($array);
$data = array();
for($i=0; $i<$size; $i++)
{
	foreach($array as $key=>$val)
		$data[] = array_slice($array, 0, $key+1);
	array_shift($array);
}

return $data;
}

?>

 

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.