2

I want to print an array without printing the square brackets and the word "Array", for example if I do

print_r($Array);

I will get this:

Array ( [0] => Example0 [1] => Example1) 

How can I get this?

Example0
Example1
5
  • Iterate over array and print each value. Commented Dec 24, 2017 at 19:23
  • @u_mulder Ok, I thought I could do this without loops Commented Dec 24, 2017 at 19:25
  • @A.Rossi You can do it without loops but only for one-dimensional arrays. Check the answer. Commented Dec 24, 2017 at 19:32
  • 1
    @Vlada903 - incorrect, as my answer shows. you can use array_walk_recursive. Commented Dec 24, 2017 at 22:01
  • @ArtisticPhoenix My mistake. Thank you for pointing it out. Commented Dec 24, 2017 at 22:14

5 Answers 5

5

Any of these ways should work just fine.

// First way
print_r(implode("<br>", $your_array));

// Second way
for ($i = 0; $i < count($your_array); $i++) { 
    print_r($your_array[$i]);
    echo "<br>";
}

// Third way
foreach ($your_array as $value) {
    print_r($value);
    echo "<br>";
}

The first method works for one-dimensional arrays only. If you have multidimensional arrays, you need to use for loops and to check whether the current element is an array or not and recursively enter into more for loops in order to print out all the data.

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

Comments

2

You can do it in this way:

function print_array ($array) {
    foreach ($array as $key => $value) {
       if (is_array ($value)) {
           print_array ($value);
       } else {
           echo ($value."<br />");
       }
    }
}

1 Comment

+1 for recursion, however the brackets around echo ($value."<br />") are not needed, echo is not a function. Think of it like break continue include etc. echo $value."<br />"; works just fine. And for us lazy programmers echo "$value<br />"; is one char shorter.
2

You could use array walk recursive

$array = ['Example0','Example1', ['Example2']];

array_walk_recursive($array,function($item,$key){echo"$item\n";});
// tip use <br> instead of \n for HTML

Outputs

Example0
Example1
Example2

See it online

array_walk_recursive — Apply a user function recursively to every member of an array

So this will seamlessly handle multi-dimensional arrays, as my example shows.

Comments

1

If I understood correctly, you want to print the values for each key. You can use

foreach ($Array as $value) {
    print_r($value);
    echo "\n";
}

This will result in

Example0
Example1

1 Comment

Merry Christmas to you too !
1
foreach($Array as $key) {
  echo $key.", ";
}

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.