Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

ความแตกต่างระหว่าง isset() และ !empty() ใน PHP


ฟังก์ชัน Isset

ISSET ตรวจสอบตัวแปรว่าถูกตั้งค่าแล้วหรือไม่ กล่าวคือ ตรวจสอบว่าตัวแปรเป็นค่าใดๆ ยกเว้น NULL หรือไม่ได้กำหนดค่า ISSET คืน TRUE หากตัวแปรมีอยู่และมีค่าอื่นนอกจาก NULL หมายถึงตัวแปรที่กำหนด "", 0, "0", หรือ FALSE ถูกตั้งค่า และจึงเป็น TRUE สำหรับ ISSET

ตัวอย่าง

<?php    $val = '0';    if( isset($val)) {       print_r(" $val is set with isset function <br>");    }    $my_array = array();    echo isset($my_array['New_value']) ?    'array is set.' : 'array is not set.'; ?>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

0 is set with isset function array is not set.

ฟังก์ชัน !empty

EMPTY ตรวจสอบว่าตัวแปรว่างเปล่าหรือไม่ Empty ถูกแปลว่า: "" (สตริงว่าง), 0 (integer), 0.0 (float), "0" (string), NULL, FALSE, array() (อาร์เรย์ว่าง), และ "$var;" (ตัวแปรที่ประกาศแต่ไม่มีค่าในคลาส)

ตัวอย่าง

<?php    $temp_val = 0;    if (empty($temp_val)) {       echo $temp_val . ' is considered empty';    }    echo "nn";    $new_val = 1;    if (!empty($new_val)) {       echo $new_val . ' is considered set';    } ?>

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

0 is considered empty 1 is considered set