JDS
JDS

Reputation: 16978

PHP string to integer question

Quick question:

I have strings in the form of '121', '9998', etc. They are literally numbers surrounded by the single quotes.

How can I remove these quotes and cast them as integers? I'm passing to another program that needs them to be integers.

Thanks.

Upvotes: 0

Views: 2633

Answers (3)

Jason McCreary
Jason McCreary

Reputation: 72961

There are a few ways to do this, but the most common are:

$int = intval($string);

Or, my preference:

$int = (int)$string;

Since $string has a literal single quote, you can trim() it first by taking advantage of its second parameter.

$int = (int)trim($string, "'");

Remember that PHP is a weak typed, dynamic language.

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 476940

Use trim() and intval():

$n = intval(trim($str, "'"));

Upvotes: 4

zerkms
zerkms

Reputation: 254886

$int = (int)trim("'121'", "'");

Upvotes: 3

Related Questions