Converting a string to an integer with PHP

Published on 2023-10-13 • Modified on 2023-10-13

This snippet shows how to convert a string to an integer with PHP. Here, we want to extract the "5" from this URL. Problem: there is a query string, but the trick here is that when we do the integer cast, PHP will look for the numeric stuff at the beginning of the string and strip all after the first non-numerical caracters (included). Use this with care!


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet279Trait
{
    public function snippet279(): void
    {
        $url = 'https://symfony.com/5?foo=bar&query=string&1=2';
        echo $url.PHP_EOL;
        $baseName = basename($url);
        echo 'Basename: '.$baseName.PHP_EOL;
        echo 'Symfony version: '.(int) $baseName;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!