1

This is driving me crazy and definitely fits into some sort of stupid question category, but for some reason my minds gone completely blank. I KNOW there is a simple way to do this, a default PHP function even, but I can't find it.

If anyone can help, there's some easy points for you.

I have an array like this:

array(
    'oauth_consumer_key'        =>  "mykey",
    'oauth_signature'           =>  "mysignature",
    'oauth_signature_method'    =>  "HMAC-SHA1",
    'oauth_timestamp'           =>  1452103343
);

I want to turn it into this:

echo someFunction($data);
// returns
// 'oauth_consumer_key="mykey", oauth_signature="mysignature", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1452103343"'

Can anyone point me in the right direction?

3
  • 1
    You can use array_map() to loop through keys and values at once, and make an array with "key => value" elements, which you then can implode() into a comma separated list; If you get stuck, post the attempt here. Commented Jan 6, 2016 at 18:20
  • Is there not a built in function similar to http_build_query? I'm sure there is a simpler way, unless i'm going mad Commented Jan 6, 2016 at 18:22
  • 1
    PHP doesn't provide you: build_me_a_yellow_pink_striped_house() function, but it does give you a hammer(), screwdriver(), ... Commented Jan 6, 2016 at 18:23

3 Answers 3

2

There are multiple functions you could try.

  1. array_map() is one of them. You can use this function with a combination of something like implode() to get what you want but it is a little complicated since your mind has gone blank haha.

  2. print_r() will print out your array with keys and values. Simple to use.

  3. var_dump() same behavior as print_r() except it will give you key and value types as well.

  4. Or you could use json_encode() which will return you as string as you say you want.

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

Comments

0

Try the built-in PHP function print_r. It will pretty-print the array for you.

Or, if you want an in-memory variable, you can do something like:

function array_to_string($array) {
    $acc = "";
    foreach($array as $key => $value) {
        $acc = $acc.$key.'='.$value.', ';
    }
    return substr($acc, 0 -1);
}

Comments

0

Yes its very simple you can use like that

function yourrequirement($yourArr){
    foreach($yourArr as $key => $value){
         echo " ' " .$key. "  = ".'"'.$value.'",'."'";
    }
}

//Call your function
yourrequirement($yourArr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.