Jump to content

Archived

This topic is now archived and is closed to further replies.

nyi8083

Convert a string to an integer

Recommended Posts

Does this function exist in PHP? I have been searching for this function for a while or any mention of it but have come up with nothing.  I'm using the $_GET['whatever'] to pass variables via the URL, and I am just not sure if that variable which is going to be a number needs to be converted to an integer if i want to use it to access part of an array.

for example, could this hypothetically work? ($a is an array)

$desc = $a[$_GET['whatever']];

I am assuming it will not, but my knowledge of php is very limited

Share this post


Link to post
Share on other sites
in my opinion, if you're expecting a number and you recieve a string, you should reject the data but since you asked, there are two things you can do:

1. settype()
[code=php:0]
settype($_GET['whatever'] , "integer");
[/code]

2. type cast
[code=php:0]
$_GET['whatever'] = (integer) $_GET['whatever'];
[/code]

Share this post


Link to post
Share on other sites
PHP is a typeless language, for the most part.
[quote]
for example, could this hypothetically work? ($a is an array)

$desc = $a[$_GET['whatever']];
[/quote]
Yes, that works fine.

Also, remember:
[code]<?php
$str_three = '3';
$three = 3;
$six = $str_three + $three;
echo $six;
?>[/code]

For more information, read this section in the find manual... http://www.php.net/manual/en/language.types.string.php

Ken

Share this post


Link to post
Share on other sites
ok thanks for the clarification

thats cool how strings and ints sort of intertwine, kind of mindblowing (i was expecting some ToInt() function similar to Koobi's suggestion)
but i think i can get used to that

Share this post


Link to post
Share on other sites
yeah, PHP would still treat it as a string, but try this:

[code=php:0]
$data = 'php';
$data = (integer) $data;

echo $data;
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.