Kim
Kim

Reputation: 1156

Get values from PHP array

I created a foreach loop in PHP like this:

foreach( $value as $element_content => $content ) {

  $canvas_elements = "<div id='" . $element_id . "'>" . $content . "</div>";  
  $elements[] = $canvas_elements;

}

So I get the values in a PHP array like this:

print_r($elements);

But this gives the results:

Array ( [0] =>
Text to edit
[1] =>
Text to edit
) 

But I only want this output and not Array ( [0] => etc:

<div id="element_id1"></div>
<div id="element_id2"></div>

How is this done?

Upvotes: 0

Views: 82

Answers (4)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Why bother with the array, if you want nothing but echo/print out some markup:

foreach( $value as $element_content => $content )
{
    echo "<div id='" . $element_id . "'>" . $content . "</div>";  
}

Whill do, however, if you insist on using that array:

echo implode('', $elements);

turns the array into a string, just like you wanted it to. Your using print_r is not the way forward, as it's more of a debug function: check the docs

Prints human-readable information about a variable

Just a little detail: you don't seem to be declaring $elements as an array anywhere. PHP will create a new variable, and assign it an empty array for you, true enough, but if you change your ini settings to E_STRICT | E_ALL, you'll notice that it doesn't do this without complaining about it. (and rrightfully so)
It's always better to declare and initialize your variables beforehand. writing $elements = array(); isn't hard, nor is it very costly. At any rate it's less costly than producing a notice.

Upvotes: 1

Zeigen
Zeigen

Reputation: 126

$elements = array();
foreach( $value as $element_content => $content ) {
    $canvas_elements = "<div id='" . $element_id . "'>" . $content . "</div>"; 
    $elements[] = $canvas_elements;
}
echo $mergedStrArray = implode("\n", $elements);

Can you try for me, Does it work?

Upvotes: 0

KarelG
KarelG

Reputation: 5244

print_r($array) is a function to display the value of the variable to the user. it's created for debugging purposes. If you want to have a HTML output, please use "echo" or something particular.

foreach( $value as $element_content => $content ) {
    echo "<div id='" . $element_id . "'>" . $content . "</div> \n";
}

Upvotes: 0

liyakat
liyakat

Reputation: 11853

use like this

<?php 
 $data = array('a'=>'apple','b'=>'banana','c'=>'orange');
 $string = implode("<br/>", $data);
 ?>
<pre><?php print_r($string); ?></pre>

OUTPUT

apple
banana
orange

Upvotes: 0

Related Questions