简体   繁体   中英

How do use a variable in a php echo to pass an id to a div?

I am creating a random musical note generator using PHP and HTML. I have placed all the positions for the musical notes in a css file and would like to do something like this:

echo 'div id=note_array[rand_numbs[1]]  class="note_1st"> &#x2669; </div>';    

The note array provides something like id="E", or id="A". Of course, it doesn't work. Is there anyway to pass a variable in echo as an id for a tag?

You have error in the concatenation and your open div, also I guess note_array[rand_numbs[1]] is an array and should be $note_array['rand_numbs'][1]

echo '<div id="'.$note_array['rand_numbs'][1].'" class="note_1st"> &#x2669; </div>';   

I prefer write it in this way

echo "<div id='{$note_array['rand_numbs'][1]}' class='note_1st'> &#x2669; </div>";   

Try echo 'div id='.note_array[rand_numbs[1]].' class="note_1st"> ♩ '; echo 'div id='.note_array[rand_numbs[1]].' class="note_1st"> ♩ ';

I think you should be able to echo it like so:

echo 'div="' . note_array[rand_numbs[1]] . '" class="note_1st"';

Using dot notation you can "glue" together a string that contains a variable or a piece of an array like you're doing here.

Instead of this:

echo 'div id=note_array[rand_numbs[1]]  class="note_1st"> &#x2669; </div>';

use this:

echo 'div id="' . note_array[rand_numbs[1]] . '"  class="note_1st"> &#x2669; </div>';

You need to enclose the value of id into quotes, also you can use dot notation to solve your problem.

Also, you can use dot notation at any string in php.

With echo , you can use the dot (.) and the comma (,). This last is sometimes more pratical than the dot. It's more easier to write the code with it. Also, you didn't always need concatenation and you can get better performance (a few).

Of course, your code will not work also if you forget the $ . I guess too such like Emilio Gort that the note_array is in fact a var (an array). So, to solve your issue, I think you can do something like this :

echo '<div id="',$note_array['rand_numbs'],'" class="note_1st"> &#x2669; </div>';

You didn't mention the content of your array. It isn't clear for me. So, you will maybe need to add some changes such like this :

echo '<div id="',$note_array['rand_numbs']['1'],'" class="note_1st"> &#x2669; </div>';
echo '<div id="',$note_array['rand_numbs']['SomethingeElse'],'" class="note_1st"> &#x2669; </div>';

You can use ['1'] or [1] . The both syntax will work. The first is supposed to allow some better performance.

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