简体   繁体   中英

how to check the length of the php array in javascript

I have two div 1st div contains some value and second div has the
php array which is fetching from the backend. i want to check on page load that if the array is empty or it contains some value using the javascript. if it contains the value i should minimize the 1st div else it should expand. code:

<div class="firstdiv ">
  <div >
    <p class="jb_text"><?php echo $per->name;?></p><hr>
  </div>
</div>

<div class="seconddiv ">
    <div class="panel-group" >
      <?php if($data): ?>
        <?php foreach($data as $work): ?>
          <div class="panel panel-default" id = "transp">
           <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 cd-name text-capitalize"><?php echo $work->first_name." ".$work->last_name; ?>
           </div>   
          </div> 
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
</div>

how to check the length of the php array in javascript.

You can't "count the php array with javascript". Php is server side, javascript is client side. That being said, you can count the displayed element by the php foreach .

To do so, with Jquery you can go with :

if(!$('.panel panel-default').length) {
    $('.seconddiv').hide();
}

in browser you need to count the div or element by class in this case

<script>
seconddivLength = document.querySelectorAll(".panel.panel-default").length;
alert("seconddiv Length is: " + seconddivLength)
</script>

You can't count a PHP array with Javascript.

Try something like this though.

   <div class="firstdiv ">
      <div >
        <p class="jb_text"><?php echo $per->name;?></p><hr>
      </div>
    </div>

    <div class="seconddiv ">
        <div class="panel-group" >
          <?php if(isset($data) && is_array($data) && count($data) >= 1): ?>
            <?php foreach($data as $work): ?>
              <div class="panel panel-default" id = "transp">
               <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 cd-name text- 
   capitalize"><?php echo $work->first_name." ".$work->last_name; ?>
               </div>   
              </div> 
            <?php endforeach; ?>
          <?php else: ?>
            <!-- What ever else you want if its empty -->
          <?php endif; ?>
        </div>
    </div>

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