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
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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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 )
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.