Using isset in php

isset

Если переменная была удалена с помощью unset() , то она больше не считается установленной. isset() вернет FALSE , если проверяемая переменная имеет значение NULL . Следует помнить, что NULL -байт («\0») не является эквивалентом константе PHP NULL .

Если были переданы несколько параметров, то isset() вернет TRUE только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределенная переменная.

Список параметров

Возвращаемые значения

Возвращает TRUE , если var определена и значение отличное от NULL , и FALSE в противном случае.

Список изменений

Проверка нечислового индекса строки теперь возвращает FALSE .

Примеры

Пример #1 Пример использования isset()

// Проверка вернет TRUE, поэтому текст будет напечатан.
if (isset( $var )) echo «Эта переменная определена, поэтому меня и напечатали.» ;
>

// В следующем примере мы используем var_dump для вывода
// значения, возвращаемого isset().

var_dump (isset( $a )); // TRUE
var_dump (isset( $a , $b )); // TRUE

var_dump (isset( $a )); // FALSE
var_dump (isset( $a , $b )); // FALSE

$foo = NULL ;
var_dump (isset( $foo )); // FALSE

Функция также работает с элементами массивов:

$a = array ( ‘test’ => 1 , ‘hello’ => NULL , ‘pie’ => array( ‘a’ => ‘apple’ ));

var_dump (isset( $a [ ‘test’ ])); // TRUE
var_dump (isset( $a [ ‘foo’ ])); // FALSE
var_dump (isset( $a [ ‘hello’ ])); // FALSE

Читайте также:  Php mysql поля update

// Элемент с ключом ‘hello’ равен NULL, поэтому он считается неопределенным
// Если Вы хотите проверить существование ключей со значением NULL, используйте:
var_dump ( array_key_exists ( ‘hello’ , $a )); // TRUE

// Проверка вложенных элементов массива
var_dump (isset( $a [ ‘pie’ ][ ‘a’ ])); // TRUE
var_dump (isset( $a [ ‘pie’ ][ ‘b’ ])); // FALSE
var_dump (isset( $a [ ‘cake’ ][ ‘a’ ][ ‘b’ ])); // FALSE

Пример #2 isset() и строковые индексы

В PHP 5.4 был изменен способ обработки строковых индексов в isset() .

$expected_array_got_string = ‘somestring’ ;
var_dump (isset( $expected_array_got_string [ ‘some_key’ ]));
var_dump (isset( $expected_array_got_string [ 0 ]));
var_dump (isset( $expected_array_got_string [ ‘0’ ]));
var_dump (isset( $expected_array_got_string [ 0.5 ]));
var_dump (isset( $expected_array_got_string [ ‘0.5’ ]));
var_dump (isset( $expected_array_got_string [ ‘0 Mostel’ ]));
?>

Результат выполнения данного примера в PHP 5.3:

bool(true) bool(true) bool(true) bool(true) bool(true) bool(true)

Результат выполнения данного примера в PHP 5.4:

bool(false) bool(true) bool(true) bool(true) bool(false) bool(false)

Примечания

isset() работает только с переменными, поэтому передача в качестве параметров любых других значений приведет к ошибке парсинга. Для проверки определения констант используйте функцию defined() .

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.

Смотрите также

  • empty() — Проверяет, пуста ли переменная
  • __isset()
  • unset() — Удаляет переменную
  • defined() — Проверяет существование указанной именованной константы
  • Таблица сравнения типов
  • array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
  • is_null() — Проверяет, является ли значение переменной равным NULL
  • Оператор управления ошибками @

Источник

PHP isset() Function

Check whether a variable is empty. Also check whether the variable is set/declared:

Читайте также:  What are html converters

$a = 0;
// True because $a is set
if (isset($a)) echo «Variable ‘a’ is set.
«;
>

$b = null;
// False because $b is NULL
if (isset($b)) echo «Variable ‘b’ is set.»;
>
?>

Definition and Usage

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL.

This function returns true if the variable exists and is not NULL, otherwise it returns false.

Note: If multiple variables are supplied, then this function will return true only if all of the variables are set.

Tip: A variable can be unset with the unset() function.

Syntax

Parameter Values

Parameter Description
variable Required. Specifies the variable to check
. Optional. Another variable to check

Technical Details

Return Value: TRUE if variable exists and is not NULL, FALSE otherwise
Return Type: Boolean
PHP Version: 4.0+
PHP Changelog: PHP 5.4: Non-numeric offsets of strings now returns FALSE

❮ PHP Variable Handling Reference

Источник

Isset in PHP Function With Examples

Isset in PHP Function With Examples

The isset in PHP is a built-in PHP function that checks if a variable is set or not. It simply means that it should be declared and not be NULL.

In this article, we will talk about PHP isset function in a detailed explanation as well as example programs that could be helpful to your future projects. This topic is a continuation of the previous topic, entitled PHP pathinfo Function.

What is Isset in PHP?

In PHP, isset is a function which use to determine once a variable is already declared and it is different than null. The isset function also checks if the declared array or array keys and variable have a null value. If it doesn’t declare, isset will return false otherwise false.

 $var2 = null; // False because $var2 is NULL if (isset($var2)) < echo "Variable 'Second Variable' is set."; >?>
Variable 'First Variable' is set.

What can I use instead of isset in PHP?

The ! empty() function can also e used instead of isset function they have the same functionalities in terms of checking a variable if they contain a value or null.

 echo "\n"; // It returns true since $new exist $new = 1; if (!empty($new)) < echo $new . ' is considered set'; >?>
0 is considered empty 1 is considered set

Why Isset is used?

The isset in PHP is always used for determining if the variable is set or not. Further, this function is also used to determine if you have used a variable in your entire code or not.

Читайте также:  Номера элементов массива питон

What is the difference between isset() and empty()?

The difference between isset and empty function is very simple, The isset is used to check if the variable is set and is not null. While the empty function is used to determine if the variable is not empty.

Summary

In summary, you have learned about isset in PHP function. This article also discussed what is Isset in PHP, what can we use instead of isset, why Isset is used, and what is the difference between isset() and empty().

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Leave a Comment Cancel reply

You must be logged in to post a comment.

Источник

Оцените статью