0

I have a variable

$placement = "1st place"

What I want to do is take the number 1 and place it in another variable

$placement_num = "1";

Is this possible?

Barmar
  • 741,623
  • 53
  • 500
  • 612
T.C
  • 311
  • 3
  • 16
  • It is possible via a few different methods. But what about cases like `"1st place, 2nd place"` -- what would your variable contain then? – Michael Berkowski Oct 04 '18 at 16:39
  • @MichaelBerkowski That may be irrelevant, we don't know how this string is generated. – GrumpyCrouton Oct 04 '18 at 16:40
  • 1
    For your simple example, merely calling `intval('1st place')` would return the desired result. – Michael Berkowski Oct 04 '18 at 16:40
  • I tried intval($placement) and it returned zero but it should have been 2 – T.C Oct 04 '18 at 19:10
  • Nevermind! I realized I had `' '` around my variable, so it was `intval('$placement')` and after removing the `' '` it worked as it should. Thank you! If you answer the question I will check it as a right answer if you like. – T.C Oct 04 '18 at 19:13

1 Answers1

0

If you know the numerical part is always right at the start of the string, you can just cast to int:

$str = '1st place';
$num = (int) $str;
var_dump($num);

$str = '4th place';
$num = (int) $str;
var_dump($num);

This yields:

int(1)
int(4)
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98