3

I have this php array:

$items = array (
    "Item 1" => "Value 1",
    "Item 2" => "Value 2",
    "Item 3" => "Value 3"
);

And I am wondering if there is an elegant PHP function I have never heard of to do the same as this:

$output = "";
foreach ( $items as $key => $value ) {
    $output .= sprintf( "%s: %s\n" , $key , $value );
}
echo $output;

Which of course, would output:

Item 1: Value 1
Item 2: Value 2
Item 3: Value 3

Also, what do you call that? Deserialization?

13
  • 4
    do you need something like var_dump or print_r ? Commented Jun 30, 2013 at 23:40
  • 3
    This wouldn't really output what you want since you reaffect $output to the current value every time. Commented Jun 30, 2013 at 23:42
  • there are scripts to format print_r, but you may as well do it as above, looks fine to me Commented Jun 30, 2013 at 23:42
  • if you are looking for a way to print array to be visually nice, use echo '<pre>'; print_r(array); echo '</pre>'; Commented Jun 30, 2013 at 23:43
  • 2
    It should be with ".=" isn't it? So: $output .= sprintf(); Commented Jun 30, 2013 at 23:44

2 Answers 2

8

There is always the array_walk function. Your example might look something like this:

function test_print($value, $key) {
    echo sprintf( "%s: %s\n" , $key , $value );
}

$items = array (
    "Item 1" => "Value 1",
    "Item 2" => "Value 2",
    "Item 3" => "Value 3"
);

array_walk($items, 'test_print');

After defining your function, you can then reuse array_walk($items, 'test_print'); as needed throughout your code.

There is also the array_walk_recursive function, if you're dealing with multidimensional arrays.

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

2 Comments

This is a really great way to do it. I like simplifying it a bit, it makes the code more understandable.
echo sprintf() is an antipattern which should never exist in any codebase for any reason. It just makes sense to replace it with the simpler, more logical equivalent: printf().
1

There is nothing wrong with your solution except that you're missing a concatenation operator.

$output = "";
foreach ( $items as $key => $value ) {
    $output .= sprintf( "%s: %s\n" , $key , $value );
}
echo $output;

Bare in mind that this only handles single dimension arrays.

There are so many built-in functions in PHP that we sometimes forget that we actually have to write code. It was mentioned in the comments that you could use one of the array_* functions, such as array_reduce, but that will only lead to more complexity compared to your solution.

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.