1

After much search (and finding endless posts about multidims, but no single dims) I thought I'd ask this question.

I have an array

$arr = array('foo' => 'bar');

and am looking for an output of

$str = 'foo bar';

This MUST be a one liner, no recursive loops etc etc etc, I am thinking that its going to have to be a lambda of some sort or another. This array will NEVER have more than a single key and a single value though.

I think its going to end up looking something like

$arr = array('foo' => 'bar');
echo 'Authorization: '  . array_walk($arr, function ($v, $k) { echo "$k $v"; });

which unfortunately ends up as foo barAuthorization: 1

no idea where the 1 comes from =P

6
  • 3
    "no idea where the 1 comes from" : array_walk returns a Boolean value, in your case true which is converted to 1 upon string concatenation. See php.net/manual/en/function.array-walk.php. Commented Feb 21, 2013 at 1:30
  • oh you want pairs to string... Commented Feb 21, 2013 at 1:31
  • your array_walk is outputting the pairs; you want it to create the string and return it instead. Commented Feb 21, 2013 at 1:32
  • Out of interest, why do you need this in one line? Commented Feb 21, 2013 at 1:34
  • 1
    Why are you using echo if it needs to go into the CURLOPT_HTTPHEADER parameter? Commented Feb 21, 2013 at 1:42

3 Answers 3

7

This should be quite easy since the array was just initialized and the pointer resides at the beginning of the array:

echo 'Authorization: ' . key($arr) . ' ' . current($arr);

Of course if you have already read data from the array you would want to do a reset() before doing this to return the pointer to the beginning of the array.

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

1 Comment

Yep works great, waiting to accept =) I forgot that key() existed
-1

PHP processes the function before it processes the string in front of it. Try replacing echo in your function with return. I think the 1 comes from the successfull processing of the array_walk function.

echo 'Authorization: '  . array_walk($arr, function ($v, $k) { return "$k $v"; });

UPDATE: Check out Example#1 http://php.net/manual/en/function.key.php

2 Comments

The return value of the callback is just ignored. array_walk always returns a Boolean.
Then he should iterate over the function with a foreach or something I guess.
-3

"This array will NEVER have more than a single key and a single value though"

echo 'Authorization: '  .  array_shift(array_keys($arr)). ' ' . array_shift($arr) ; 

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.