Home >Backend Development >PHP Tutorial >How Can I Convert a String to a Number in PHP?

How Can I Convert a String to a Number in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 19:39:16402browse

How Can I Convert a String to a Number in PHP?

Converting a String to a Number in PHP

Unlike JavaScript's Number() method, PHP lacks a direct function to convert strings to numbers. However, PHP allows for type coercion in various situations.

Type Casting for Explicit Conversion

In cases where explicit conversion is required, casting can be employed using the following syntax:

  • (int)$string: Converts the string to an integer.
  • (float)$string: Converts the string to a floating-point number.

For instance, consider the following conversions:

$num = "3.14";
$int = (int)$num; // Result: 3
$float = (float)$num; // Result: 3.14

PHP's Automatic Type Coercion

In most instances, PHP will automatically coerce types during operations. For example:

$num = "2";
$total = $num + 10; // $total will be 12 (an integer)

The above is the detailed content of How Can I Convert a String to a Number in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn