PHP

PHP

Installation

Ubuntu
apt install php
AlmaLinux
dnf install php
Arch Linux
pacman -S php
Source Code
# Download php-{version}.tar.gz from https://php.net
./configure [options]... [VAR=VALUE]...
make
make test
make install

Examples

Fibonacci Numbers
<?php
/**
 * Fibonacci Numbers
 * @param int $n
 * @return int
 */
function fib($n) {
    if ($n < 2) {
        return $n;
    } else {
        return fib($n-2) + fib($n-1);
    }
}

print fib($argv[1]);

/*
example
    run:
        php fib_php.php 39
*/

Memoization

<?php
/**
 * Fibonacci Numbers
 * @param int $n
 * @return int
 */
function fib($n) {
    static $f = [0, 1];
    return $f[$n] ?? ($f[$n] = fib($n-2) + fib($n-1));
}

print fib($argv[1]);

/*
example
    run:
        php fib_php.php 39
*/

Tail Recursive

<?php
/**
 * Fibonacci Numbers
 * @param int $n
 * @param int $p1 = 1
 * @param int $p2 = 0
 * @return int
 */
function fib($n, $p1 = 1, $p2 = 0) {
    if ($n == 0) {
        return 0;
    } elseif ($n == 1) {
        return $p1;
    } else {
        return fib($n - 1, $p1 + $p2, $p1);
    }
}

print fib($argv[1]);

/*
example
    run:
        php fib_tail.php 39
*/

FFI

// Fibonacci Numbers Shared Object
const int fib(int n)
{
    if (n < 2) {
        return n;
    } else {
        return fib(n - 2) + fib(n - 1);
    }
}

/*
Example
    compile:
        gcc -O3 -fPIC -o libfib.so libfib.c
*/
<?php
/**
 * Fibonacci Numbers
 * libffi
 */
$ffi = FFI::cdef("
const int fib(int n);
", "./libfib.so");

print $ffi->fib(intval($argv[1]));

/*
example
    run:
        php fib_ffi.php 39
*/