简体   繁体   中英

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?

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 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.

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

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";
}
$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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM