Jump to content

Switching values with keys.


DarkWater

Recommended Posts

I know that I should know this, because I feel like there is a function like it, but I can't remember if there is.  Is there a function that takes the values of an array and turns it into keys for that array, if the values are strings?  You know, now that I think about it, that does sound odd.  There might not even be a function that does it.  I'll code one if there isn't.

 

Basically, I need an opposite version of array_keys(). >_>

Link to comment
https://forums.phpfreaks.com/topic/102342-switching-values-with-keys/
Share on other sites

i think ur after somthing like this ?

<?
foreach($_GET as $key => $value) 
{

	$$key = $value;

}
?>

 

Almost.  But I'm going to make sure each string is shorter than a certain # of chars and some other things if I do write a function for it.

I know u know :P how to write it, but im posting my solution of swapping keys with values :) :

 

<?php
$arr = array('me' => 'guiltygear', 'you' => 'darkwater');
$keys = array_keys($arr);
$values = array_values($arr);
$arr = array_combine($values, $keys);
?>

 

;D

OH, there is an array_values() function.  That would have helped.  But I finished already. =D

<?php
function flip_array($array_flip, $max_lengthofkey=10) {
//Usage: array flip_array(array $array_flip, scalar $max_lengthofkey)
if ((!is_array($array_flip)) || (!is_scalar($max_lengthofkey))) {
	return false;
}
      	foreach ($array_flip as $k => $v) {
	if (!is_string($v)) {
		continue;
	}
	if (strlen($v) > $max_lengthofkey) {
		$v = substr($v, 0, $max_lengthofkey); 
	}
	$new_array[$v]=$k;
}
return $new_array;
}
$oldarray = array("test"=>"dog", "test2"=>"cat");
$newarray=flip_array($oldarray);
print_r($newarray); //Outputs Array ( [dog] => test [cat] => test2 )
?>

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.