<?php

error_reporting(-1);

$array = [1, 2, 3, 4];

function getFactorial($array){
	$factorial = 1;
	for($n = 1; $n<=count($array); $n++){
		$factorial *= $n;
	}
	return $factorial;
}

$factorial = getFactorial($array);

function getCombinations($array){
	$output = [];
	if(count($array) == 2){
		$iterations = 2;
	} else {
		$iterations = count($array) * 2;
		$halfIterations = $iterations / 2;
	}
	while($iterations > 0){
		$combination = [];
		foreach($array as $key => $value){
			$firstKey = array_key_first($array);
			if($key == array_key_last($array)){
				$combination[$key] = $array[$firstKey];
			} else {
				$combination[$key] = next($array);
			}
		}
		if($iterations <= $halfIterations){
			krsort($combination);
		}
		$array = $combination;
		$output[] = $combination;
		$iterations--;
	}
	return $output;
}

function Main($array){
	$str = "";
	$count = (count($array) - 1);
	if(count($array) == 1){
		return $array;
	} else {
		for($n = 0; $n <= $count; $n++){
			$cutElement = $array[$n];
			unset($array[$n]);
			$combinations = getCombinations($array, $factorial);
			foreach($combinations as $key => $value){
				array_unshift($combinations[$key], $cutElement);
				$str .= implode(" ", $combinations[$key]);
				$str .= "\n";
			}
			$array[$n] = $cutElement;
		}
	}
	return $str;
}

$res = Main($array);
echo $res;