3

Say you have an array like this...

username, password, email

and you need to assign a value to each element. After, this needs to be formatted into a string like this:

username=someRandomValueAssigned&password=someRandomValueAssigned&email=someRandomValueAssigned

how would I do this? Thanks.

4 Answers 4

7
$keys = array('username', 'password', 'email');

$values = array('someusername', 'somepassword', 'someemail');

$data = array_combine($keys, $values);

array_combine will return an associative array like,

$data = array( 
          'username' => 'someusername',
          'password' => 'somepassword',
          'email' => 'someemail'
        );

then the result you want can be achieved using a simple foreach loop

$str = '';

foreach($data as $k=>$v) {
   $str .= $k > 0 ? '&' : '';
   $str .= $k . '=' . $v ;
}

echo $str;

Also, I suspect you are trying to build a url so you might want to check out php's http_build_query function

Sign up to request clarification or add additional context in comments.

2 Comments

Well, it's not an associative array to start out with. It's just a string I broke into an array "this, that, thisthat"; I now need to assign a value to each of those variable, then put the array back together into a string and format it like a URL.
Ok, have edited the answer now. I hope this is what you are looking for.
1
$array_value=array();
$array_value['username']=somevalue;
$array_value['password']=somevalue;
$array_value['email']=somevalue;
$array_str=array();
foreach($array_value as $key=>$value){
   array_push($array_str,$key."=".$array_value[$value]);
}
$array_str=join("&",$array_str);
echo $array_str;

Comments

1

Looks like you're building a query string, I think you want to use http_build_query():

$data = array(
    'username'  =>  'someRandomValueAssigned',
    'password'  =>  'someRandomValueAssigned',
    'email'     =>  'someRandomValueAssigned',
);

$query_string = http_build_query($data);

This should give you the result you're looking for.

http_build_query — Generate URL-encoded query string

http://php.net/manual/function.http-build-query.php

Comments

0
$randomValue = array('username' => 'someValue' ); // same for other
foreach($array as &$value){
  $value = $value.'='.$randomValue[$value];
}

echo implode('&', $array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.