It’s commonly referred to as ‘shorthand’ or the Ternary Operator.
In PHP 7 you can write it even shorter:
That’s called a ternary operator and it’s mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
Of course it’s not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
You have encountered the ternary operator. It’s purpose is that of a basic if-else statement. The following pieces of code do the same thing.
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you’re looking at is called a Ternary Operator, and you can find the PHP implementation here. It’s an if else statement.
If you want an empty string default then a preferred way is one of these (depending on your need):
. &something=+++&key2=value (parameter is » » )
Why this is a preferred approach:
Update Strict mode may require something like this:
isset — Определяет, была ли установлена переменная значением отличным от NULL
Описание
Определяет, была ли установлена переменная значением отличным от NULL
Если были переданы несколько параметров, то isset() вернет TRUE только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределенная переменная.
Список параметров
Возвращаемые значения
Список изменений
Версия
Описание
5.4.0
Примеры
Пример #1 Пример использования isset()
// В следующем примере мы используем var_dump для вывода // значения, возвращаемого isset().
$a = «test» ; $b = «anothertest» ;
Функция также работает с элементами массивов:
Пример #2 isset() и строковые индексы
Результат выполнения данного примера в PHP 5.3:
Результат выполнения данного примера в PHP 5.4:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.
isset — Определяет, была ли установлена переменная значением, отличным от null
Описание
Определяет, была ли установлена переменная значением отличным от null
Если были переданы несколько параметров, то isset() вернёт true только в том случае, если все параметры определены. Проверка происходит слева направо и заканчивается, как только будет встречена неопределённая переменная.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования isset()
// В следующем примере мы используем var_dump для вывода // значения, возвращаемого isset().
$a = «test» ; $b = «anothertest» ;
Функция также работает с элементами массивов:
Пример #2 isset() и строковые индексы
Результат выполнения данного примера:
Примечания
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.
При использовании isset() на недоступных свойствах объекта, будет вызываться перегруженный метод __isset(), если он существует.
Смотрите также
User Contributed Notes 30 notes
I, too, was dismayed to find that isset($foo) returns false if ($foo == null). Here’s an (awkward) way around it.
Of course, that is very non-intuitive, long, hard-to-understand, and kludgy. Better to design your code so you don’t depend on the difference between an unset variable and a variable with the value null. But «better» only because PHP has made this weird development choice.
In my thinking this was a mistake in the development of PHP. The name («isset») should describe the function and not have the desciption be «is set AND is not null». If it was done properly a programmer could very easily do (isset($var) || is_null($var)) if they wanted to check for this!
The new (as of PHP7) ‘null coalesce operator’ allows shorthand isset. You can use it like so:
You can safely use isset to check properties and subproperties of objects directly. So instead of writing
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.
«empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.»
!empty() mimics the chk() function posted before.
in PHP5, if you have
I tried the example posted previously by Slawek:
$foo = ‘a little string’; echo isset($foo)?’yes ‘:’no ‘, isset($foo[‘aaaa’])?’yes ‘:’no ‘;
He got yes yes, but he didn’t say what version of PHP he was using.
I tried this on PHP 5.0.5 and got: yes no
But on PHP 4.3.5 I got: yes yes
Any foreach or similar will be different before and after the call.
To organize some of the frequently used functions..
Return Values : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
isset expects the variable sign first, so you can’t add parentheses or anything.
With this simple function you can check if an array has some keys:
If you regard isset() as indicating whether the given variable has a value or not, and recall that NULL is intended to indicate that a value is _absent_ (as said, somewhat awkwardly, on its manual page), then its behaviour is not at all inconsistent or confusing.
Here is an example with multiple parameters supplied
Note that isset() is not recursive as of the 5.4.8 I have available here to test with: if you use it on a multidimensional array or an object it will not check isset() on each dimension as it goes.
Imagine you have a class with a normal __isset and a __get that fatals for non-existant properties. isset($object->nosuch) will behave normally but isset($object->nosuch->foo) will crash. Rather harsh IMO but still possible.
// pretend that the methods have implementations that actually try to do work // in this example I only care about the worst case conditions
// if property does not exist < echo «Property does not exist!» ; exit; // > >
$obj = new FatalOnGet ();
Uncomment the echos in the methods and you’ll see exactly what happened:
On a similar note, if __get always returns but instead issues warnings or notices then those will surface.
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.
The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:
?>
Outputs: True False Notice: Undefined variable: j in filename.php on line 26
This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.
У меня есть странный случай, когда скрипт должен получать значения 2-х параметров время от времени. Один из параметров — гео, а другой — приливы, и мне нужно разбить приливы на 4 разные переменные для моего использования. Я хотел бы установить условие, при котором параметр geo может всегда присутствовать в запрошенном URL, а приливы могут не присутствовать. Это было бы возможно с оператором ИЛИ «||»? На данный момент у меня есть
По сути, я хочу сказать, чтобы скрипт действовал по-своему, если он помещен в POST с параметрами tids и geo, а если нет — обрабатывают как обычно для отдельных приливов 1, 2, 3 и 4, а географическое местоположение отправляется другим способом с другими параметры. Если я попытаюсь отделить их запятой (,) вместо этого или оператором ИЛИ (||), это означает, что должны присутствовать все условия, т. Е. Чтобы приливы и гео всегда отправлялись в скрипт, иначе скрипт не будет обрабатываться, если только геопараметр установлен. Как настроить его на обработку, если присутствует геопараметр, но приливов может не быть? Дело в том, что некоторые другие скрипты могут передавать данные для tid1, 2, 3, 4 и т. Д. Отдельно в различных параметрах tid1, tid2, tid3 и tid, а geo извлекается изнутри с помощью другой переменной, и из некоторых других источников я получаю все Приливы, смешанные с разделителем в одну строку и расположение в качестве параметра гео. Вот почему я хочу различать случаи в одном и том же сценарии без необходимости копировать один и тот же сценарий с другим именем, чтобы различать случаи, и чтобы отдельные API вызывали разные файлы, потому что им приходится обрабатывать данные по-разному.
Решение
Я думаю, что вы пытаетесь сказать, если я оба сделаю это, если у меня есть только один, сделайте другой? Если это так, это должно сделать это, или, по крайней мере, направить вас в правильном направлении.
Другие решения
Вы можете использовать Вложенные IF заявления. Попробуйте код ниже
Надеюсь это поможет.
Я провел обширное тестирование, и похоже, что написанный мною код действительно выполняет свою работу, а ошибка была в другом месте. Спасибо всем за то, что вложили время и энергию в помощь мне, ответив! Очень признателен.
I have a form on one page that submits to another page. There, it checks if the input mail is filled. If so then do something and if it is not filled, do something else. I don’t understand why it always says that it is set, even if I send an empty form. What is missing or wrong?
15 Answers 15
Most form inputs are always set, even if not filled up, so you must check for the emptiness too.
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
empty space is considered as set. You need to use empty() for checking all null options.
You can simply use:
Your new code will be:
I think you need it for your database, so you can assign your HTML Form Value to php Variable, now you can use Real Escape String and below must be your
Check to see if the FORM has been submitted first, then the field. You should also sanitize the field to prevent hackers.
To answer the posted question: isset and empty together gives three conditions. This can be used by Javascript with an ajax command as well.
Not the answer you’re looking for? Browse other questions tagged php isset or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.