user2562568
user2562568

Reputation: 367

PHP converting variable string to int

To start, I could not find this answer online because of the way my variable string is defined. Normally I should be able to add 0 to the variable, or use (int), but it does not work.

<?php

$casestringid = "'118'";
$caseid = $casestringid + 0;

echo $casestringid;

echo $caseid;

?>

Output: '118'0

As you can see, because of the way my first variable is declared, the standard methods of converting a string to an integer does not work. My $casestringid is written like that because it requests a number from another page. Rather than trying to change how to format that, I figure it will be easier for help on how to convert a string that looks like that, into an integer. I would like the output of caseid to be 118. Thanks for any help in advance.

Upvotes: 0

Views: 206

Answers (7)

Shawn G.
Shawn G.

Reputation: 622

If it is just an integer you are looking for, this could work. it will remove any non digit characters then return it as an int

function parseInt( $s ){
    return (int)(preg_replace( '~\D+~' , '' , $s ));
}

Upvotes: 0

Nerius
Nerius

Reputation: 980

Try intval ($casestringid) + 0.

EDIT:

How about this, then:

filter_var ($casestringid, FILTER_SANITIZE_NUMBER_INT);

Upvotes: 1

federicot
federicot

Reputation: 12331

The problem is that '118' is not an integer as far as the PHP parser is concerned, it's a string. It looks like an integer to us, of course, but it has slashes (') which make it "unconvertible".

Use str_replace for this:

intval(str_replace("'", '', $casestringid));

Upvotes: 3

robz228
robz228

Reputation: 640

$casestringid = "'118'";
$int = str_replace("'", "", $casestringid);
echo intval($int);

Upvotes: 0

Zaziki
Zaziki

Reputation: 418

Replace the '':

intval(str_replace("'",'',$casestringid));

Upvotes: 1

steven
steven

Reputation: 4875

i think you have no other chance like this:

intval(str_replace("'",'',$casestringid));

Upvotes: 1

theftprevention
theftprevention

Reputation: 5213

You have to remove the single quotes and use intval().

<?php

$casestringid = "'118'";
$parseid = str_replace("'", "", $casestringid);
$caseid = intval($parseid);

echo $casestringid;

echo $caseid;

?>

Upvotes: 0

Related Questions