The use of the PHP question-mark expression

Source: Internet
Author: User
The existing variable, which may be of a time type, may be a Unix timestamp, i.e. $time = '2011-12-25 00:11:20';Or $time = 1324742400.

Now I want to make a transformation of unity, that is 时间类型 , if it is, it is converted to a Unix timestamp by a strtotime($time) function, if not the same function strtotime($time) will return false .

Then I use question mark expression $time = strtotime($time) ? strtotime($time) : $time; can achieve this demand, there is no more concise form ah, always feel that others do not write it?

Reply content:

The existing variable, which may be of a time type, may be a Unix timestamp, that is, $time = '2011-12-25 00:11:20'; or $time = 1324742400 .

Now I want to make a transformation of unity, that is 时间类型 , if it is, it is converted to a Unix timestamp by a strtotime($time) function, if not the same function strtotime($time) will return false .

Then I use question mark expression $time = strtotime($time) ? strtotime($time) : $time; can achieve this demand, there is no more concise form ah, always feel that others do not write it?

The main reason why people don't write like this is that if you do this time , you can do two functions if it's actually a time format strtotime .
You can use temporary variables to solve this problem

$temp = strtotime($time);$time = $temp ? $temp : $time;

If PHP is above 5.3, you can also use

$time = strtotime($time) ?: $time;

There's a place in your question. I'm not sure, if it's a string timestamp, must the format be the Y-m-d H:i:s format?

$time = is_numeric($time) ? $time : strtotime($time);

In fact, there is no need for ternary operators, directly using && can be

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.