My point was mostly that the solution that uses (sub)strings is known and documented and using tools that are meant for strings. But using string to int casting you’re potentially opening yourself up to weird PHP behaviours. Now here it’s probably fine, but in general I tend to keep things in the datatype that I got them in, until I’m certain that what I’ve massaged it to is convertable to the target datatype, before actually casting it. For example, what if PHP decided that mathematical operators in strings must be parsed to, all of a sudden 1/2
would be 0.5
rather than 1
. Unlikely, but casting is far less strict defined than functions (at least in my opinion).
I would certainly check against that beforehand. This would be my production version:
function getFirstPart(string $x) {
$pos = strpos('/', $x);
if (false === $pos) {
throw new InvalidArgumentException('getFirstPart expects argument in format X/Y/Z');
}
$part = substr($x, 0, $pos + 1);
if (!ctype_digit($part)) {
throw new InvalidArgumentException(sprintf('First part of "%s" passed to getFirstPart was expected to be number, got "%s"', $x, $part);
}
return (int) $part;
}
Overkill? Maybe, depends on the usecase. In cases where a borked string without any numbers would result in the price of something being sold would be zero then I would take the above over casting any day of the week.
The main advantage of this approach, even though it might seem a bit much, is that I can be sure that whatever comes out is something that’s useful. It’s not based on assumptions that the input will always adhere to some pattern and will stop with useful messages whenever it’s not, rather than moving forward fist first with data that’s incorrect causing who knows what kind of havoc in the system.