Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

How to concatenate increment operator to PHP

  $i = 0;
while ($slider_query->have_posts()) {
              $slider_query->the_post();
              $html ='<div class= "col-lg-3 order-lg-'.$i.' col-md-6 p-0">';
                 $html .= '<div class= "ss-pic">';
                    $html .= '<img src="'.get_the_post_thumbnail_url(get_the_ID(), 'full').'"/>';
                $html .='</div>';
             $html .='</div>';
             $html ='<div class= "col-lg-3 order-lg-"'.++$i.'"col-md-6 p-0">';
                $html .= '<div class= "ss-text">';
                    $html .= '<h3>'.get_the_title().'</h3>';
                    $html .= get_the_content();
                    $html .= '<a href="/gym">Explore</a>';
                
            $html .='</div>';
         $html .='</div>';

I want to pre-increment the $i. Can anyone please help me out? I know its a basic, but I have a bit of confusion over the concatenation

question from:https://stackoverflow.com/questions/65559646/how-to-concatenate-increment-operator-to-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So firstly you can pre-increment an integer variable by prepending ++ to it, e.g.

++$i

. That will work for you, e.g.

'<div class= "col-lg-3 order-lg-'.++$i.' col-md-6 p-0">'

However, you also have another problem which is preventing you from seeing the results as you are expecting. Every time you write $html = - which is twice within your loop, you overwrite the contents of $html. The previous contents of the variable are destroyed. Therefore, at whatever time you come to echo $html to the output, you'll only ever see the last version.

You need to concatenate all the HTML together into a single string without overwriting it.

Put

$html = "";

just before the loop starts, and then change

$html ='<div class= "col-lg-3 order-lg-'.$i.' col-md-6 p-0">';

to

$html .='<div class= "col-lg-3 order-lg-'.++$i.' col-md-6 p-0">';

(note the .= there, and also the ++$i which you forgot)

and lower down, change

$html ='<div class= "col-lg-3 order-lg-"'.++$i.'"col-md-6 p-0">';

to

$html .='<div class= "col-lg-3 order-lg-"'.++$i.'"col-md-6 p-0">';

(again just changing the = to .=.)

Demo: http://sandbox.onlinephpfunctions.com/code/7e1ac7b039867eedd22d90dfcdc03e8990419a8f


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...