2012-07-05 61 views
1

在我的功能是這樣的:檢查選擇的值是最後一個數組

function ypg_delete_img($id, $img) 
     { 
      $q = $this->ypg_get_one($id); 

      $imgs = explode(',', $q->image); 

      if(count($imgs) > 1) : 
       $z = ","; 
      else : 
       $z = ""; 
       $data['image'] = 'avatar_mali_oglas.png'; 
       $this->db->where('id_yellow_pages', $id); 
       $this->db->update('yellow_pages', $data); 
      endif; 
      if($imgs[0] != 'avatar_mali_oglas.png') : 
       $query = "UPDATE `yellow_pages` "; 
       $query .= "SET `image` = REPLACE(`image`,'". $img . $z ."', '') 
          WHERE `id_yellow_pages` = $id "; 
       $this->global_functions->delete_img('zute_strane', $img); 
      $this->db->query($query); 
      endif; 
     } 

我需要檢查,如果$ IMG$ IMGS數組中的最後一個值。我怎樣才能做到這一點?

回答

6

使用end()

if ($img == end($imgs)) { 
    // $img is the last element of the array 
} 
+0

這是行得通的。感謝您的幫助:) – Sasha 2012-07-05 10:12:53

0

請參考下面的代碼。

if($imgs[count($imgs) -1] == $img) 
{ 
    // $img is the last image 
} 

希望這會有所幫助:)

+0

這可能會導致性能問題。 – 2012-07-05 10:14:05

0

像這樣的東西應該工作:

<?php 
    $lastitem = array_pop($imgs); 
    if ($img == $lastitem) { 
    // is last image 
    } 
?> 

array_pop返回數組的最後一個元素,在第在你只需要比較兩個值。