Last Updated:

Formatting string in PHP | Example

Formatting string in PHP example

The PHP language provides many simple ways to convert strings into numbers. One condition is that the string must consist solely of numeric characters. If the string

 consists of a set of letter characters, then it is only possible to get its length (length) or the character code in numerical format (intchar\int[] chars).

 

Arithmetic operator "+" and transformation through "(int)"

This operator can translate from docu to number without using built-in functions. Let's break this down the string value:

<?php
$int_1 = +"100"; \\ putting the operator + in front of the line — we get the conversion of the string to the number
$int_2 = "100" + 0; \\ when you add a string, it is converted to a number. We saved the value by adding a line with zero
$int_3 = 0 + "100"; \\ swapped zero and the
string $int_4 = (int)"100"; \\ explicit conversion using the operator (int)

\\ the var_dump($var) function returns the type of a variable and indicates its value in parentheses

echovar_dump($int_1); \\ int(100)
echovar_dump($int_2); \\ int(100)
echovar_dump($int_3); \\ int(100)
echovar_dump($int_4); \\ int(100)
?>

Conversion using the intval() function

The intval(var) function takes any type as a parameter and converts it to an integer:

<?php
$str = "100";
$int_from_str = intval($str); \\ Translate the value in the str variable into a number and store it in another variable
echovar_dump($int_from_str); \\ int(100)
<?

Settype() function

 

The settype(var, type) function converts one variable type to another. The first parameter inserts the variable or literal that you want to convert, the second parameter specifies which type to convert to - sring, integer, float, boolean, etc.

Example:

<?php
$str = "100";
$str = settype($str, «integer»); \\ integer is a string parameter surrounded by
quotation marks echovar_dump($str); \\ int(100)
?>

What happens if you apply all of these features to a character string?

Any operation performed on a character string will be zero. It does not matter whether the plus is placed before the line, whether the row is multiplied by a number, or whether an explicit transformation occurs using functions or (int).

The result will always be the same. And if you apply the var_dump() function, the result will be int(0), in some cases int(NaN) — Not a Number. This value is obtained by multiplying a number by a word or by arithmetic operations between character strings and numbers.

The most universal operator for converting a number to a string is "+", put before the line: +"44". This construct always translates a string into a number in all languages of the C family.