1

I have a url that will look as follows.

post/:id

I am exploding the $_SERVER['REQUEST_URI'];

and I need to make the $uri[2] is numerical so I can do things like

$next = $uri[2]++;

I have tried is_numeric but of course the request_uri is a string (broken into an array of strings).

Can I type cast in php to integer?

ChrisW
  • 4,970
  • 7
  • 55
  • 92
James Vince
  • 1,269
  • 3
  • 10
  • 12

4 Answers4

3
$int = (int) $uri[2];

You just have to convert from string to integer.

David
  • 3,831
  • 2
  • 28
  • 38
1

Have you tried intval(): http://php.net/manual/en/function.intval.php?

int intval(mixed $var [, int $base = 10 ])

"Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1."

UPDATE

Having wondered what the difference between (int) $string and intval($string) is, there are some interesting comments on previous SO questions;

Community
  • 1
  • 1
ChrisW
  • 4,970
  • 7
  • 55
  • 92
0

Just to clarify both David and ChrisW are correct. Those are two ways of doing it as described at http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting

<?php

$str = '100';

var_dump( $str ); // string(3) "100"

// http://php.net/manual/en/function.intval.php
var_dump( intval($str) ); // int(100)

// http://php.net/manual/en/language.types.type-juggling.php
var_dump( (int) $str ); // int(100)

?>
Community
  • 1
  • 1
Anthony Hatzopoulos
  • 10,437
  • 2
  • 40
  • 57
0

you can just take it as a number from url passing argument in as a $_GET request.

Or pass through as a $_POST request.

But in the case of $_POST request we cann't pass the value to url. if you want you can using $_SERVER['REQUEST_URI'] and convert to (int) $_GET['pid'].