Eğer php ifadesi soru

4 Cevap

Ben başka ürün varsa öğelerin bir dizi var ve kontrol etmek gerekiyor bir if deyimi var.

Yani, örneğin

foreach($id_cart as $id) {
if(($id == 4 || $id == 5) && **IF ANY OTHER ITEM EXISTS**){
    echo "Yes";
}

Is there a simple way of doing that? An item exists or it does not. $id_cart will have, let's say, ids: 4,5,6,8,12,14 There is nothing else stored. So if 4 or 5 are there, plus any other number...

4 Cevap

If your question is asking "I have a list of ids, from which I want to know if one is there, and apart of that one, if other items exist", one course of action could be the following:

  • if the item you look for exists, remove it from the array and check if it still has any members
    • if count(array) is > 0 do this; else do that;
  • Başka yoktu veya 'yalnız' oldu.

Eylem bu ders çok iyileştirilebilir: örneğin, orijinal dizi her tekrarda üye kaybedecek. Eğer dizi içeren üyeleri umurumda değil eğer kolay bir değişikliği sadece count(array) - 1 yapmak olacaktır.

Belki de bu ne isterseniz yapar:

foreach ($id_cart as $id) {
    if (($id == 4 || $id == 5) && count(array_diff($id_cart, array(4, 5)))) {
        // do something
    }
}

ya da, daha iyisi:

if ((in_array(4, $id_cart) || in_array(5, $id_cart)) && count(array_diff($id_cart, array(4, 5)))) {
   // four or five exists, while other elements are also in the array
   // do something
}

Bu 4 veya 5 olmayan öğeleri bulabilirsiniz

$others = array_diff($id_cart, array(4, 5));

Bu kimin tuşları 4 veya 5 olmayan öğeleri bulabilirsiniz

$others = array_diff_key($id_cart, array_flip(array(4, 5)));

Verimli bir şekilde dizinin anahtarları kimliklerini saklamak ve isset () ile kendi varlığı için kontrol etmektir.

PHP's arrays are dictionaries. Take advantage of this feature, instead of wasting time with in_array().