How to get only the version number of php?

Extending Jeff Schaller's answer, skip the pipeline altogether and just ask for the internal constant representation:

$ php -r 'echo PHP_VERSION;'
7.1.15

You can extend this pattern to get more, or less, information:

$ php -r 'echo PHP_MAJOR_VERSION;'
7

See the PHP list of pre-defined constants for all available.

The major benefit: it doesn't rely on a defined output format of php -v. Given it's about the same performance as a pipeline solution, then it seems a more robust choice.


If your objective is to test for the version, then you can also use this pattern. For example, this code will exit 0 if PHP >= 7, and 1 otherwise:

php -r 'exit((int)version_compare(PHP_VERSION, "7.0.0", "<"));'

For reference, here are timings for various test cases, ordered fastest first:

$ time for (( i=0; i<1000; i++ )); do php -v | awk '/^PHP [0-9]/ { print $2; }' >/dev/null; done

real    0m13.368s
user    0m8.064s
sys     0m4.036s

$ time for (( i=0; i<1000; i++ )); do php -r 'echo PHP_VERSION;' >/dev/null; done

real    0m13.624s
user    0m8.408s
sys     0m3.836s

$ time for (( i=0; i<1000; i++ )); do php -v | head -1 | cut -f2 -d' ' >/dev/null; done

real    0m13.942s
user    0m8.180s
sys     0m4.160s

If you've installed php via the package manager (e.g. RPM or yum), then you can query the version from there:

rpm -q --queryformat="%{VERSION}" php

Alternatively, you can ask php to tell you its version directly:

php -r 'echo phpversion();'

On my system:

$> php -v | grep ^PHP | cut -d' ' -f2
7.0.32-0ubuntu0.16.04.1

as grep PHP matches every PHP string it encounters.

The ^PHP means "match only the string 'PHP' when it is at the start of a line".

Obviously, this works if the output format of php -v is consistent across versions/builds.

For reference, the whole output was:

PHP 7.0.32-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.32-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies

Tags:

Php

Version