Php convert 0 to null

Conversions

Explicit type conversion is performed using the cast operator. If an operation or language construct expects operand of one type and a value of another type is given, implicit (automatic) conversion will be performed. Same will happen with most internal functions, though some functions may do different things depending on argument type and thus would not perform the conversion.

If an expression is converted to its own type, the type and value of the result are the same as the type and value of the expression.

Conversions to resource and null types can not be performed.

Converting to Boolean Type

The [result type] (http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting) is bool .

If the source type is int or float , then if the source value tests equal to 0, the result value is FALSE ; otherwise, the result value is TRUE .

If the source value is NULL , the result value is FALSE .

If the source is an empty string or the string “0”, the result value is FALSE ; otherwise, the result value is TRUE .

If the source is an array with zero elements, the result value is FALSE ; otherwise, the result value is TRUE .

If the source is an object, the result value is TRUE .

If the source is a resource, the result value is TRUE .

The library function boolval allows values to be converted to bool .

Converting to Integer Type

If the source type is bool , then if the source value is FALSE , the result value is 0; otherwise, the result value is 1.

If the source type is float , for the values INF , -INF , and NAN , the result value is zero. For all other values, if the precision can be preserved (that is, the float is within the range of an integer), the fractional part is rounded towards zero. If the precision cannot be preserved, the following conversion algorithm is used, where X is defined as two to the power of the number of bits in an integer (for example, 2 to the power of 32, i.e. 4294967296):

  1. We take the floating point remainder (wherein the remainder has the same sign as the dividend) of dividing the float by X, rounded towards zero.
  2. If the remainder is less than zero, it is rounded towards infinity and X is added.
  3. This result is converted to an unsigned integer.
  4. This result is converted to a signed integer by treating the unsigned integer as a two’s complement representation of the signed integer.

Implementations may implement this conversion differently (for example, on some architectures there may be hardware support for this specific conversion mode) so long as the result is the same.

If the source value is NULL , the result value is 0.

If the source is a numeric string or leading-numeric string having integer format, if the precision can be preserved the result value is that string’s integer value; otherwise, the result is undefined. If the source is a numeric string or leading-numeric string having floating-point format, the string’s floating-point value is treated as described above for a conversion from float . The trailing non-numeric characters in leading-numeric strings are ignored. For any other string, the result value is 0.

If the source is an array with zero elements, the result value is 0; otherwise, the result value is 1.

If the source is an object, if the class defines a conversion function, the result is determined by that function (this is currently available only to internal classes). If not, the conversion is invalid, the result is assumed to be 1 and a non-fatal error is produced.

If the source is a resource, the result is the resource’s unique ID.

The library function intval allows values to be converted to int .

Converting to Floating-Point Type

If the source type is int , if the precision can be preserved the result value is the closest approximation to the source value; otherwise, the result is undefined.

If the source is a numeric string or leading-numeric string having integer format, the string’s integer value is treated as described above for a conversion from int . If the source is a numeric string or leading-numeric string having floating-point format, the result value is the closest approximation to the string’s floating-point value. The trailing non-numeric characters in leading-numeric strings are ignored. For any other string, the result value is 0.

If the source is an object, if the class defines a conversion function, the result is determined by that function (this is currently available only to internal classes). If not, the conversion is invalid, the result is assumed to be 1.0 and a non-fatal error is produced.

For sources of all other types, the conversion result is obtained by first converting the source value to int and then to float .

The library function floatval allows values to be converted to float.

Converting to String Type

If the source type is bool , then if the source value is FALSE , the result value is the empty string; otherwise, the result value is “1”.

If the source type is int or float , then the result value is a string containing the textual representation of the source value (as specified by the library function sprintf ).

If the source value is NULL , the result value is the empty string.

If the source is an array, the conversion is invalid. The result value is the string “Array” and a non-fatal error is produced.

If the source is an object, then if that object’s class has a __toString method, the result value is the string returned by that method; otherwise, the conversion is invalid and a fatal error is produced.

If the source is a resource, the result value is an implementation-defined string.

The library function strval allows values to be converted to string.

Converting to Array Type

If the source value is NULL , the result value is an array of zero elements.

If the source type is scalar or resource and it is non- NULL , the result value is an array of one element under the key 0 whose value is that of the source.

If the source is an object, the result is an array of zero or more elements, where the elements are key/value pairs corresponding to the object’s instance properties. The order of insertion of the elements into the array is the lexical order of the instance properties in the class-member-declarations list.

For public instance properties, the keys of the array elements would be the same as the property name.

The key for a private instance property has the form “\0class\0name”, where the class is the class name, and the name is the property name.

The key for a protected instance property has the form “\0*\0name”, where name is that of the property.

The value for each key is that from the corresponding property, or NULL if the property was not initialized.

Converting to Object Type

If the source has any type other than object, the result is an instance of the predefined class stdClass . If the value of the source is NULL , the instance is empty. If the value of the source has a scalar type and is non- NULL , or is a resource , the instance contains a public property called scalar whose value is that of the source. If the value of the source is an array, the instance contains a set of public properties whose names and values are those of the corresponding key/value pairs in the source. The order of the properties is the order of insertion of the source’s elements.

Источник

PHP RFC: Nullable Casting

PHP supports expression casting to primitive type (like int ) by using “ ( type ) expression”, but it currently doesn’t allow to use a nullable type as introduced by PHP 7.1 (e.g. ?int ).

Due to the lack of support for nullable casting, it is necessary to write additional code to preserve a possible null value through the type conversion. This feature would also bring more consistency and completeness to the existing language.

Motivating Example

function getInt(): int { return mt_rand(); } function processString(string $s): void { printf("process a string of %d byte(s)\n", strlen($s)); }

will throw a TypeError (“Argument 1 passed to processString() must be of the type string, int given”), but here we can use a cast ( int to string conversion is always safe):

processString((string) getInt());

(which will print something like “process a string of 9 byte(s)”).

Now given two functions like the following (with nullable type declarations):

function getIntOrNull(): ?int { $r = mt_rand(); return $r % 2 === 0 ? $r : null; } function processStringOrNull(?string $s): void { if ($s === null) { printf("process null\n"); } else { printf("process a string of %d byte(s)\n", strlen($s)); } }
processStringOrNull(getIntOrNull());

will sometimes work (print “process null”) and sometimes throw a TypeError (“Argument 1 passed to processStringOrNull() must be of the type string or null, int given”), so we would want to use a “nullable cast”:

processStringOrNull((?string) getIntOrNull());

but currently this syntax is not supported (“Parse error: syntax error, unexpected ‘?’”) and we must resort to something more verbose (and error-prone) like:

or writing custom casting functions.

(Note that in weak type-checking mode, there is never a TypeError , the ?int is automatically converted to ?string , correctly preserving a null value. But we can prefer strict typing, to catch unintended conversions.)

settype()

When the desired type is not known before runtime, we cannot use a cast operator, but we can use the settype() function, for example:

but currently $type cannot contain a nullable type like «?string» (“Warning: settype(): Invalid type”, $x not converted).

Proposal

The proposal is to add support of nullable types to the current casting feature. Basically, (int) is the “plain” int cast, and (?int) will be a nullable int cast. Generally speaking, what changes is the possibility to use a leading question mark symbol ( ? ) before the type of a cast, turning it into a nullable cast.

The only difference of nullable casting compared to plain casting is that if the expression value is null , it will be kept as null instead of being forced to the destination plain type:

type: int bool float string array object
( type ) null 0 false 0.0 «» [] <>
(? type ) null null null null null null null

The PHP parser is not sensitive to spaces in e.g. “ ( int ) ” cast and “ ? int ” type declaration, so e.g. “ ( ? int ) ” will be identical to “ (?int) ”.

The PHP parser does not distinguish between (integer) and (int) casts, so (?integer) will be identical to (?int) . Likewise for (?boolean) vs (?bool) , (?double) or (?real) vs (?float) , and (?binary) vs (?string) .

If the expression value is not null , nullable casting will give the same result as plain casting: e.g. (?int)false will give 0, (?array)»» will give [«»].

Additional proposal for settype()

Additionally, it was requested on the mailing list to consider adding support of nullable types to the settype() function, e.g. settype ( $variable , «?int» ) , which here would be the same as $variable = ( ?int ) $variable ; and return true (but in general «?int» could be a dynamic string).

In short, for a currently valid $type argument to settype ( $variable , $type ) , it would enable to use ‘?’ . $type to preserve nullability.

«?null»

In «?null» , the “ ? ” is redundant (“nullable null”), but it could happen in dynamic code, e.g. settype ( $x , ‘?’ . gettype ( $y ) ) when $y is null .

For demonstration, the current patch uses option 2.

Источник

Php convert 0 to null

Share and discover the latest news about the PHP ecosystem and its community. Please respect r/php’s rules.

Hi folks. Trying to dive back into PHP after a good 10 year break. Doing pretty okay but I’ve run into a road block. I’ve been writing a little login/user creation script to try some things out but I can’t seem to find any good resources or reading info on how to convert blank strings (empty form fields) into NULL. For example, the ‘phone’ field is not required but has to be unique. But if i leave it blank when testing the form, then try to create another user with a blank ‘phone’, it tell’s me the phone is already in use. This is how I am currently checking to see if the phone is already in use:

$query = » SELECT 1 FROM users WHERE phone = :phone «; $query_params = array( ‘:phone’ => $_POST[‘phone’] ); try < $stmt = $db->prepare($query); $result = $stmt->execute($query_params); > catch(PDOException $ex) < die("Failed to run query: " . $ex->getMessage()); > $row = $stmt->fetch(); if($row) < die("This phone is already registered");

And this is how I’m doing the query:

$query = » INSERT INTO users ( username, email, phone ) VALUES ( :username, :email, :phone ) «; $query_params = array( ‘:username’ => $_POST[‘username’], ‘:email’ => $_POST[’email’], ‘:phone’ => $_POST[‘phone’] ); try < $stmt = $db->prepare($query); $result = $stmt->execute($query_params); > catch(PDOException $ex) < die("Failed to run query: " . $ex->getMessage()); >

Источник

Читайте также:  Очистить данные post php
Оцените статью