Jump to content


Photo

Convert a string to an integer


  • Please log in to reply
4 replies to this topic

#1 nyi8083

nyi8083
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 01 August 2006 - 04:48 AM

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

#2 Koobi

Koobi
  • Staff Alumni
  • Advanced Member
  • 419 posts
  • LocationColombo, Sri Lanka | South Asia

Posted 01 August 2006 - 04:55 AM

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()
settype($_GET['whatever'] , "integer");

2. type cast
$_GET['whatever'] = (integer) $_GET['whatever'];


#3 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 01 August 2006 - 05:12 AM

PHP is a typeless language, for the most part.

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

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

Yes, that works fine.

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

For more information, read this section in the find manual... http://www.php.net/m...ypes.string.php

Ken

#4 nyi8083

nyi8083
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 01 August 2006 - 05:16 AM

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

#5 Koobi

Koobi
  • Staff Alumni
  • Advanced Member
  • 419 posts
  • LocationColombo, Sri Lanka | South Asia

Posted 01 August 2006 - 07:42 AM

yeah, PHP would still treat it as a string, but try this:

$data = 'php';
$data = (integer) $data;

echo $data;





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users