Asked 7 years ago
26 Apr 2017
Views 2582
noob

noob posted

how to flip array value to key without array_flip in PHP ?

it is possible to flip array value to key and key to value by single function array_flip .


$flipped_array=array_flip($array);


but how to flip array value to key without array_flip in PHP ?
Rasi

Rasi
answered Nov 30 '-1 00:00

custom array_flip function . it will flip array in one dimensional as array_flip do


function ArrayFlip($array){
	$tempd=array();
	foreach($array as $key=>$value){
		$tempd[$value]=$key;
	}
	return $tempd;
}
$array=array("A"=>"a");
$d=ArrayFlip($a);


its good alternative of array_flip PHP function .
ArrayFlip replace the common entry with last one . if you want to preserve the unique entry than following function will help


 function ArrayFlip($a){
	$tempd=array();
	foreach($a as $key=>$value){
		if(isset($tempd[$value]))
		$tempd[$value]=$key;
		else 
		$tempd[$value.rand(1,100)]=$key;
	
	}
	return $tempd;
}


for the unique value i changed it to by adding random number . you can do you way to make it visible


		$tempd[$value.rand(1,100)]=$key;



change this code in function ArrayFlip
Post Answer