# Using lpsolve from PHP

### PHP?

PHP is a general-purpose scripting language that is especially suited for web development. PHP generally runs on a web server, taking PHP code as its input and creating web pages as output. It can also be used for command-line scripting and client-side GUI applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems. It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use. PHP primarily acts as a filter, taking input from a file or stream containing text and/or PHP instructions and outputs another stream of data; most commonly the output will be HTML. It can automatically detect the language of the user. From PHP 4, the PHP parser compiles input to produce bytecode for processing by the Zend Engine, giving improved performance over its interpreter predecessor. Originally designed to create dynamic web pages, PHP's principal focus is server-side scripting, and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's ASP.NET system, Sun Microsystems' JavaServer Pages, and mod_perl. PHP has also attracted the development of many frameworks that provide building blocks and a design structure to promote rapid application development (RAD). Some of these include CakePHP, PRADO, Symfony and Zend Framework, offering features similar to other web application frameworks.

We will not discuss the specifics of PHP here but instead refer the reader to the PHP website.
An introduction to PHP can be found at w3schools

### PHP and lpsolve

lpsolve is callable from PHP via an extension or module. As such, it looks like lpsolve is fully integrated with PHP. Matrices can directly be transferred between PHP and lpsolve in both directions. The complete interface is written in C so it has maximum performance. The whole lpsolve API is implemented with some extra's specific for PHP (especially for matrix support). So you have full control to the complete lpsolve functionality via the lpsolve PHP driver. If you find that this involves too much work to solve an lp model then you can also work via higher-level script files that can make things a lot easier. See further in this article.

### Installation

To make this possible, a driver program is needed: php_phplpsolve55.dll (windows) or phplpsolve55.so (Unix/Linux).
Secondly in the file php.ini, which is a PHP configuration file, the location of the driver must be specified. The location of this ini file depends on the environment.
Under windows it is commonly \Program Files\php\php.ini
Under Unix/Linux it was found under /etc/php5/cli and /etc/php5/apache2
In that file there is an item extension_dir=. The driver program must be put in the directory specified by that item.
Then an extra entry 'extension' must be added.
Under windows it must be: extension=php_phplpsolve55.dll
Under Unix/Linux it must be: extension=phplpsolve55.so

Note that there is an alternative way but it is not always working, especially as webservice. In the php.ini file, specify enable_dl=on
Then in the PHP code, use the following command to load the lpsolve driver: dl('lpsolve.so');
However, this was not tested so use it at own risk.

To take these changes in effect, the webservice has to be restarted.
Under windows, this is done by restarting the service.
Under Unix/Linux it depends on the system. For example in Ubuntu the command is: sudo /etc/init.d/apache2 restart
This must be done with root privileges: sudo su -

This driver calls lpsolve via the lpsolve shared library (lpsolve55.dll under Windows and liblpsolve55.so under Unix/Linux) (archive lp_solve_5.5.2.14_dev.zip/lp_solve_5.5.2.14_dev.tar.gz). This has the advantage that the lpsolve driver doesn't have to be recompiled when an update of lpsolve is provided. The shared library must be somewhere in the Windows path.

So note the difference between the PHP lpsolve driver that is called (php_)phplpsolve55 and the lpsolve library that implements the API that is called lpsolve55.

### Testing the installation

Note. In the following text PHP commands are given. They are just provided as is. However in a real PHP application, all PHP commands must be between <?php and ?>

Note. Some of these commands return new lines to continue on the next line. This is fine under CLI (php executed in a command line), but when PHP is used in a web environment and shown in html, then these newlines are by default just ignored by html. This gives an output that is not always that readable. Therefore you can put everything between <pre> </pre>
This combined with the note from above, put the commands in following block:

    <?php
    echo "<pre>";
    // your php commands
    echo "</pre>";
    ?>

To test if everything is installed correctly, execute the following statement in PHP.

    lpsolve();

Note. As stated above, these commands must be between <?php and ?> and when used in html between a pre block as shown below:

    <?php
    echo "<pre>";
    lpsolve();
    echo "</pre>";
    ?>

Keep this in mind. This will not be repeated in the following text.

If it gives the following, then everything is ok:

    lpsolve PHP Interface version 5.5.0.6
    using lpsolve version 5.5.2.14

    Usage: ret = lpsolve("functionname", arg1, arg2, ...)

If you get the following:

Windows:

    PHP Warning:  PHP Startup: Unable to load dynamic library 'F:\php-5.2.6\Release_TS\php_phplpsolve55.dll' - The specified module could not be found. in Unknown on line 0
    PHP Fatal error:  Call to undefined function lpsolve() in Command line code on line 1

Possible also with a messagebox saying:

    ---------------------------
    php.exe - Unable To Locate Component
    ---------------------------
    This application has failed to start because lpsolve55.dll was not found. Re-installing the application may fix this problem.

or Unix/Linux:

    PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20060613+lfs/phplpsolve55.so' - liblpsolve55.so: cannot open shared object file: No such file or directory in Unknown on line 0

    Fatal error: Call to undefined function lpsolve() in Command line code on line 1

Note that the PHP Warning is not always shown. The Fatal error is. This was specifically noted in the web environment.

Then PHP can find the lpsolve driver program, but the driver program cannot find the lpsolve library that contains the lpsolve implementation. This library is called lpsolve55.dll under Windows and liblpsolve55.so under Unix/Linux.
Under Windows, the lpsolve55.dll file must be in a directory that in the PATH environment variable. This path can be shown via the following command in a command prompt: PATH
It is common to place this in the WINDOWS\system32 folder.
Under Unix/Linux, the liblpsolve55.so shared library must be either in the directories /lib or /usr/lib or in a directory specified by the LD_LIBRARY_PATH environment variable.

Note that in a web environment the webserver may need to be restarted after making changes in the configuration. For example on Ubuntu this is done by the following command:

    sudo /etc/init.d/apache2 restart

Another way to check if the lpsolve extension is available in PHP is by entering the following command:

    print_r(get_extension_funcs("lpsolve"));

This must return:

    Array
    (
        [0] => lpsolve
    )

To return the version of lpsolve, the following PHP command can be executed:

    echo phpversion("lpsolve");

This must return:

    5.5.0.6

Note that this is the version of the PHP driver, not the version of lpsolve itself.

### Solve an lp model from PHP via lpsolve

To call an lpsolve function, the following syntax must be used:

    ret = lpsolve('functionname', arg1, arg2, ...);

The return value is optional and depend on the function called. Sometimes it is a single value, sometimes a vector and sometimes a vector of vector. functionname must always be enclosed between single or double quotes to make it alphanumerical and it is case sensitive. The number and type of arguments depend on the function called. Some functions even have a variable number of arguments and a different behaviour occurs depending on the type of the argument. functionname can be (almost) any of the lpsolve API routines (see lp_solve API reference) plus some extra PHP specific functions. Most of the lpsolve API routines use or return an lprec structure. To make things more robust in PHP, this structure is replaced by a handle or the model name. The lprec structures are maintained internally by the lpsolve driver. The handle is an incrementing number starting from 0. Starting from driver version 5.5.0.2, it is also possible to use the model name instead of the handle. This can of course only be done if a name is given to the model. This is done via lpsolve routine set_lp_name or by specifying the model name in routine read_lp. See Using model name instead of handle.

Almost all callable functions can be found in the lp_solve API reference. Some are exactly as described in the reference guide, others have a slightly different syntax to make maximum use of the PHP functionality. For example make_lp is used identical as described. But get_variables is slightly different. In the API reference, this function has two arguments. The first the lp handle and the second the resulting variables and this array must already be dimensioned. When lpsolve is used from PHP, nothing must be dimensioned in advance. The lpsolve driver takes care of dimensioning all return variables and they are always returned as return value of the call to lpsolve. Never as argument to the routine. This can be a single value as for get_objective or a matrix or vector as in get_variables. In this case, get_variables returns a 4x1 matrix (vector) with the result of the 4 variables of the lp model.

Note that you can get a usage of lpsolve, its arguments and the constants that it defines by entering the following in PHP:

    lpsolve();
    $a=get_defined_constants(true); print_r($a[lpsolve]);

This will give:

    lpsolve  PHP Interface version 5.5.0.6
    using lpsolve version 5.5.2.14

    Usage: ret = lpsolve("functionname", arg1, arg2, ...)
    Array
    (
        [LE] => 1
        [EQ] => 3
        [GE] => 2
        [FR] => 0
        [SCALE_NONE] => 0
        [SCALE_EXTREME] => 1
        [SCALE_RANGE] => 2
        [SCALE_MEAN] => 3
        [SCALE_GEOMETRIC] => 4
        [SCALE_CURTISREID] => 7
        [SCALE_QUADRATIC] => 8
        [SCALE_LOGARITHMIC] => 16
        [SCALE_USERWEIGHT] => 31
        [SCALE_POWER2] => 32
        [SCALE_EQUILIBRATE] => 64
        [SCALE_INTEGERS] => 128
        [SCALE_DYNUPDATE] => 256
        [SCALE_ROWSONLY] => 512
        [SCALE_COLSONLY] => 1024
        [IMPROVE_NONE] => 0
        [IMPROVE_SOLUTION] => 1
        [IMPROVE_DUALFEAS] => 2
        [IMPROVE_THETAGAP] => 4
        [IMPROVE_BBSIMPLEX] => 8
        [PRICER_FIRSTINDEX] => 0
        [PRICER_DANTZIG] => 1
        [PRICER_DEVEX] => 2
        [PRICER_STEEPESTEDGE] => 3
        [PRICE_PRIMALFALLBACK] => 4
        [PRICE_MULTIPLE] => 8
        [PRICE_PARTIAL] => 16
        [PRICE_ADAPTIVE] => 32
        [PRICE_RANDOMIZE] => 128
        [PRICE_AUTOPARTIAL] => 256
        [PRICE_LOOPLEFT] => 1024
        [PRICE_LOOPALTERNATE] => 2048
        [PRICE_HARRISTWOPASS] => 4096
        [PRICE_TRUENORMINIT] => 16384
        [PRESOLVE_NONE] => 0
        [PRESOLVE_ROWS] => 1
        [PRESOLVE_COLS] => 2
        [PRESOLVE_LINDEP] => 4
        [PRESOLVE_SOS] => 32
        [PRESOLVE_REDUCEMIP] => 64
        [PRESOLVE_KNAPSACK] => 128
        [PRESOLVE_ELIMEQ2] => 256
        [PRESOLVE_IMPLIEDFREE] => 512
        [PRESOLVE_REDUCEGCD] => 1024
        [PRESOLVE_PROBEFIX] => 2048
        [PRESOLVE_PROBEREDUCE] => 4096
        [PRESOLVE_ROWDOMINATE] => 8192
        [PRESOLVE_COLDOMINATE] => 16384
        [PRESOLVE_MERGEROWS] => 32768
        [PRESOLVE_IMPLIEDSLK] => 65536
        [PRESOLVE_COLFIXDUAL] => 131072
        [PRESOLVE_BOUNDS] => 262144
        [PRESOLVE_DUALS] => 524288
        [PRESOLVE_SENSDUALS] => 1048576
        [ANTIDEGEN_NONE] => 0
        [ANTIDEGEN_FIXEDVARS] => 1
        [ANTIDEGEN_COLUMNCHECK] => 2
        [ANTIDEGEN_STALLING] => 4
        [ANTIDEGEN_NUMFAILURE] => 8
        [ANTIDEGEN_LOSTFEAS] => 16
        [ANTIDEGEN_INFEASIBLE] => 32
        [ANTIDEGEN_DYNAMIC] => 64
        [ANTIDEGEN_DURINGBB] => 128
        [ANTIDEGEN_RHSPERTURB] => 256
        [ANTIDEGEN_BOUNDFLIP] => 512
        [CRASH_NONE] => 0
        [CRASH_MOSTFEASIBLE] => 2
        [CRASH_LEASTDEGENERATE] => 3
        [SIMPLEX_PRIMAL_PRIMAL] => 5
        [SIMPLEX_DUAL_PRIMAL] => 6
        [SIMPLEX_PRIMAL_DUAL] => 9
        [SIMPLEX_DUAL_DUAL] => 10
        [NODE_FIRSTSELECT] => 0
        [NODE_GAPSELECT] => 1
        [NODE_RANGESELECT] => 2
        [NODE_FRACTIONSELECT] => 3
        [NODE_PSEUDOCOSTSELECT] => 4
        [NODE_PSEUDONONINTSELECT] => 5
        [NODE_PSEUDORATIOSELECT] => 6
        [NODE_USERSELECT] => 7
        [NODE_WEIGHTREVERSEMODE] => 8
        [NODE_BRANCHREVERSEMODE] => 16
        [NODE_GREEDYMODE] => 32
        [NODE_PSEUDOCOSTMODE] => 64
        [NODE_DEPTHFIRSTMODE] => 128
        [NODE_RANDOMIZEMODE] => 256
        [NODE_GUBMODE] => 512
        [NODE_DYNAMICMODE] => 1024
        [NODE_RESTARTMODE] => 2048
        [NODE_BREADTHFIRSTMODE] => 4096
        [NODE_AUTOORDER] => 8192
        [NODE_RCOSTFIXING] => 16384
        [NODE_STRONGINIT] => 32768
        [NOMEMORY] => -2
        [OPTIMAL] => 0
        [SUBOPTIMAL] => 1
        [INFEASIBLE] => 2
        [UNBOUNDED] => 3
        [DEGENERATE] => 4
        [NUMFAILURE] => 5
        [USERABORT] => 6
        [TIMEOUT] => 7
        [PRESOLVED] => 9
        [PROCFAIL] => 10
        [PROCBREAK] => 11
        [FEASFOUND] => 12
        [NOFEASFOUND] => 13
        [BRANCH_CEILING] => 0
        [BRANCH_FLOOR] => 1
        [BRANCH_AUTOMATIC] => 2
        [BRANCH_DEFAULT] => 3
        [MSG_PRESOLVE] => 1
        [MSG_LPFEASIBLE] => 8
        [MSG_LPOPTIMAL] => 16
        [MSG_MILPEQUAL] => 256
        [MSG_MILPFEASIBLE] => 128
        [MSG_MILPBETTER] => 512
        [NEUTRAL] => 0
        [CRITICAL] => 1
        [SEVERE] => 2
        [IMPORTANT] => 3
        [NORMAL] => 4
        [DETAILED] => 5
        [FULL] => 6
        [Infinite] => 1.0E+30
    )

The array shows all constants defined by the lpsolve driver and are all the constants of the lpsolve API. That way one can enter these symbols instead of their numerical values.

Also see Using string constants for an alternative.

### An example

(Note that you can execute this example by entering command per command as shown below or by executing script example1.php)

    $lp = lpsolve('make_lp', 0, 4);
    lpsolve('set_verbose', $lp, IMPORTANT);
    $ret = lpsolve('set_obj_fn', $lp, Array(1, 3, 6.24, 0.1));
    $ret = lpsolve('add_constraint', $lp, Array(0, 78.26, 0, 2.9), GE, 92.3);
    $ret = lpsolve('add_constraint', $lp, Array(0.24, 0, 11.31, 0), LE, 14.8);
    $ret = lpsolve('add_constraint', $lp, Array(12.68, 0, 0.08, 0.9), GE, 4);
    $ret = lpsolve('set_lowbo', $lp, 1, 28.6);
    $ret = lpsolve('set_lowbo', $lp, 4, 18);
    $ret = lpsolve('set_upbo', $lp, 4, 48.98);
    $ret = lpsolve('set_col_name', $lp, 1, 'COLONE');
    $ret = lpsolve('set_col_name', $lp, 2, 'COLTWO');
    $ret = lpsolve('set_col_name', $lp, 3, 'COLTHREE');
    $ret = lpsolve('set_col_name', $lp, 4, 'COLFOUR');
    $ret = lpsolve('set_row_name', $lp, 1, 'THISROW');
    $ret = lpsolve('set_row_name', $lp, 2, 'THATROW');
    $ret = lpsolve('set_row_name', $lp, 3, 'LASTROW');
    $ret = lpsolve('write_lp', $lp, 'a.lp');
    print lpsolve('get_mat', $lp, 1, 2) . "\n";
    print lpsolve('solve', $lp) . "\n";
    print lpsolve('get_objective', $lp) . "\n";
    print_r(lpsolve('get_variables', $lp));
    print_r(lpsolve('get_constraints', $lp));
    lpsolve('delete_lp', $lp);

This gives as output:

    78.26
    0
    31.7827586207
    Array
    (
        [0] => Array
            (
                [0] => 28.6
                [1] => 0
                [2] => 0
                [3] => 31.8275862069
            )

        [1] => 1
    )
    Array
    (
        [0] => Array
            (
                [0] => 92.3
                [1] => 6.864
                [2] => 391.292827586
            )

        [1] => 1
    )

Note that get_variables and get_constraints return two results: The result vector and a status. If only the vector is needed, then variable indexing must be used. For example:

    $ret = lpsolve('get_variables', $lp);
    $x = $ret[0];
    $ret = $ret[1];
    print_r($x);
    print $ret . "\n";

Variable x will contain the result vector and ret the return status of the call:

    Array
    (
        [0] => 28.6
        [1] => 0
        [2] => 0
        [3] => 31.8275862069
    )
    1

Don't forget to free the handle and its associated memory when you are done:

    lpsolve('delete_lp', $lp);

### Using model name instead of handle

From driver version 5.5.0.2, it is possible to use the model name instead of the handle. From the moment the model has a name, you can use this name instead of the handle. This is best shown by an example. Above example would look like this:

    $lp = lpsolve('make_lp', 0, 4);
    $ret = lpsolve('set_lp_name', $lp, 'mymodel');
    lpsolve('set_verbose', 'mymodel', IMPORTANT);
    $ret = lpsolve('set_obj_fn', 'mymodel', Array(1, 3, 6.24, 0.1));
    $ret = lpsolve('add_constraint', 'mymodel', Array(0, 78.26, 0, 2.9), GE, 92.3);
    $ret = lpsolve('add_constraint', 'mymodel', Array(0.24, 0, 11.31, 0), LE, 14.8);
    $ret = lpsolve('add_constraint', 'mymodel', Array(12.68, 0, 0.08, 0.9), GE, 4);
    $ret = lpsolve('set_lowbo', 'mymodel', 1, 28.6);
    $ret = lpsolve('set_lowbo', 'mymodel', 4, 18);
    $ret = lpsolve('set_upbo', 'mymodel', 4, 48.98);
    $ret = lpsolve('set_col_name', 'mymodel', 1, 'COLONE');
    $ret = lpsolve('set_col_name', 'mymodel', 2, 'COLTWO');
    $ret = lpsolve('set_col_name', 'mymodel', 3, 'COLTHREE');
    $ret = lpsolve('set_col_name', 'mymodel', 4, 'COLFOUR');
    $ret = lpsolve('set_row_name', 'mymodel', 1, 'THISROW');
    $ret = lpsolve('set_row_name', 'mymodel', 2, 'THATROW');
    $ret = lpsolve('set_row_name', 'mymodel', 3, 'LASTROW');
    $ret = lpsolve('write_lp', 'mymodel', 'a.lp');
    print lpsolve('get_mat', 'mymodel', 1, 2) . "\n";
    print lpsolve('solve', 'mymodel') . "\n";
    print lpsolve('get_objective', 'mymodel') . "\n";
    print_r(lpsolve('get_variables', 'mymodel'));
    print_r(lpsolve('get_constraints', 'mymodel'));
    lpsolve('delete_lp', 'mymodel');

This gives:

    78.26
    0
    31.7827586207
    Array
    (
        [0] => Array
            (
                [0] => 28.6
                [1] => 0
                [2] => 0
                [3] => 31.8275862069
            )

        [1] => 1
    )
    Array
    (
        [0] => Array
            (
                [0] => 92.3
                [1] => 6.864
                [2] => 391.292827586
            )

        [1] => 1
    )

So everywhere a handle is needed, you can also use the model name. You can even mix the two methods. There is also a specific PHP routine to get the handle from the model name: get_handle.
For example:

    $lp = lpsolve('get_handle', 'mymodel');
    print $lp;

This gives:

    0

Don't forget to free the handle and its associated memory when you are done:

    lpsolve('delete_lp', 'mymodel');

In the next part of this documentation, the handle is used. But if you name the model, the name could thus also be used.

### Matrices

lpsolve uses PHP arrays to represent matrices (and vectors).
For example:

    lpsolve('add_constraint', $lp, Array(0.24, 0, 11.31, 0), 1, 14.8);

Most of the time, variables are used to provide the data:

    lpsolve('add_constraint', $lp, $a1, 1, 14.8);

Where $a1 is a variable of type array. Sometimes a two-dimensional matrix is used. In PHP, that is an array of arrays:

    lpsolve('set_mat', $lp, Array(Array(1, 2, 3), Array(4, 5, 6)));

Array(1, 2, 3) is the first row and Array(4, 5, 6) is the second row.

PHP also supports sparse matrices because of the way arrays are internally supported.
For example:

    $a[2] = 3;
    $a[5] = 5;

    print_r($a);

This gives:

    Array
    (
        [2] => 3
        [5] => 5
    )

The lpsolve driver accepts these as is. No conversion or so is needed. The non-provided elements are seen as zero-values.

In fact, the lpsolve driver sees all provided matrices as sparse matrices. lpsolve uses sparse matrices internally and data can be provided sparse via the ex routines. For example add_constraintex. The lpsolve driver always uses the ex routines to provide the data to lpsolve. Even if you call from PHP the routine names that would require a dense matrix (for example add_constraint), the lpsolve driver will always call the sparse version of the routine (for example add_constraintex). This results in the most performing behaviour.

An important final note. Several lp_solve API routines accept a vector where the first element (element 0) is not used. Other lp_solve API calls do use the first element. In the PHP interface, there is never an unused element in the matrices. So if the lp_solve API specifies that the first element is not used, then this element is not in the PHP matrix.

### Maximum usage of matrices with lpsolve

Because PHP has the array possibility to represent vectors, all lpsolve API routines that need a column or row number to get/set information for that column/row are extended in the lpsolve PHP driver to also work with vectors. For example set_int in the API can only set the integer status for one column. If the status for several integer variables must be set, then set_int must be called multiple times. The lpsolve PHP driver however also allows specifying a vector to set the integer status of all variables at once. The API call is: $return = lpsolve('set_int', $lp, $column, $must_be_int);. The matrix version of this call is: $return = lpsolve('set_int', $lp, $must_be_int);. Here $must_be_int must be an array variable. The API call to return the integer status of a variable is: $return = lpsolve('is_int', $lp, $column);. The matrix version of this call is: $is_int = lpsolve('is_int', $lp);
$is_int is again an array variable in this case. Also note the get_mat and set_mat routines. In PHP these are extended to return/set the complete constraint matrix. See following example.

Above example can thus also be done as follows:
(Note that you can execute this example by entering command per command as shown below or by executing script example2.php)

    $lp = lpsolve('make_lp', 0, 4);
    lpsolve('set_verbose', $lp, IMPORTANT);
    $ret = lpsolve('set_obj_fn', $lp, Array(1, 3, 6.24, 0.1));
    $ret = lpsolve('add_constraint', $lp, Array(0, 78.26, 0, 2.9), GE, 92.3);
    $ret = lpsolve('add_constraint', $lp, Array(0.24, 0, 11.31, 0), LE, 14.8);
    $ret = lpsolve('add_constraint', $lp, Array(12.68, 0, 0.08, 0.9), GE, 4);
    $ret = lpsolve('set_lowbo', $lp, Array(28.6, 0, 0, 18));
    $ret = lpsolve('set_upbo', $lp, Array(Infinite, Infinite, Infinite, 48.98));
    $ret = lpsolve('set_col_name', $lp, Array('COLONE', 'COLTWO', 'COLTHREE', 'COLFOUR'));
    $ret = lpsolve('set_row_name', $lp, Array('THISROW', 'THATROW', 'LASTROW'));
    $ret = lpsolve('write_lp', $lp, 'a.lp');
    print_r(lpsolve('get_mat', $lp));
    print lpsolve('solve', $lp) . "\n";
    print lpsolve('get_objective', $lp) . "\n";
    print_r(lpsolve('get_variables', $lp));
    print_r(lpsolve('get_constraints', $lp));
    lpsolve('delete_lp', $lp);

This gives:

    Array
    (
        [0] => Array
            (
                [0] => Array
                    (
                        [0] => 0
                        [1] => 78.26
                        [2] => 0
                        [3] => 2.9
                    )

                [1] => Array
                    (
                        [0] => 0.24
                        [1] => 0
                        [2] => 11.31
                        [3] => 0
                    )

                [2] => Array
                    (
                        [0] => 12.68
                        [1] => 0
                        [2] => 0.08
                        [3] => 0.9
                    )

            )

        [1] => 1
    )
    0
    31.7827586207
    Array
    (
        [0] => Array
            (
                [0] => 28.6
                [1] => 0
                [2] => 0
                [3] => 31.8275862069
            )

        [1] => 1
    )
    Array
    (
        [0] => Array
            (
                [0] => 92.3
                [1] => 6.864
                [2] => 391.292827586
            )

        [1] => 1
    )

Note the usage of Infinite in set_upbo. This stands for 'infinity'. Meaning an infinite upper bound. It is also possible to use -Infinite to express minus infinity. This can for example be used to create a free variable. Infinite is a constant defined by the lpsolve library.

To show the full power of the matrices, let's now do some matrix calculations to check the solution. It works further on above example. Note that PHP doesn't support much matrix calculations on arrays. We only need a matrix multiplication routine to demonstrate the following. For this the following routine can be used. Include it in the next code to perform the matrixmultiply:

    function matrixmultiply($Array1, $Array2) {
            $rows2 = count($Array2);
            if (is_array($Array2[0])) {
                $dim2 = 2;
                $columns2 = count($Array2[0]);
            }
            else {
                $dim2 = 1;
                $columns2 = 1;
            }

            $rows1 = count($Array1);
            if (is_array($Array1[0])) {
                $dim1 = 2;
                $columns1 = count($Array1[0]);
            }
            else {
                $dim1 = 1;
                if ($rows2 == 1)
                    $columns1 = 1;
                else {
                    $columns1 = $rows1;
                    $rows1 = 1;
                }
            }

            for($i=0; $i<$rows1; $i++){
                    for($j=0; $j<$columns2; $j++){
                            $a = 0;
                            for($M=0;$M<$columns1;$M++){
                                    if ($dim1 == 2)
                                        $b = $Array1[$i][$M];
                                    else if ($rows2 == 1)
                                        $b = $Array1[$i];
                                    else
                                        $b = $Array1[$M];
                                    $c = $Array2[$M];
                                    if ($dim2 == 2)
                                        $c = $c[$j];
                                    $a = $a + $b * $c;
                            }
                            if ($dim2 == 2)
                                $ArrayMultipli[$i][$j] = $a;
                            else
                                $ArrayMultipli[$i] = $a;
                    }
            }
            return $ArrayMultipli;
    }

Now do the following calculations:

    $lp = lpsolve('make_lp', 0, 4);
    lpsolve('set_verbose', $lp, IMPORTANT);
    $ret = lpsolve('set_obj_fn', $lp, Array(1, 3, 6.24, 0.1));
    $ret = lpsolve('add_constraint', $lp, Array(0, 78.26, 0, 2.9), GE, 92.3);
    $ret = lpsolve('add_constraint', $lp, Array(0.24, 0, 11.31, 0), LE, 14.8);
    $ret = lpsolve('add_constraint', $lp, Array(12.68, 0, 0.08, 0.9), GE, 4);
    $ret = lpsolve('set_lowbo', $lp, Array(28.6, 0, 0, 18));
    $ret = lpsolve('set_upbo', $lp, Array(Infinite, Infinite, Infinite, 48.98));
    $ret = lpsolve('set_col_name', $lp, Array('COLONE', 'COLTWO', 'COLTHREE', 'COLFOUR'));
    $ret = lpsolve('set_row_name', $lp, Array('THISROW', 'THATROW', 'LASTROW'));
    $ret = lpsolve('write_lp', $lp, 'a.lp');
    lpsolve('solve', $lp);

    $A = lpsolve('get_mat', $lp);
    $A = $A[0];
    print_r($A);
    $X = lpsolve('get_variables', $lp);
    $X = $X[0];
    print_r($X);
    $B = matrixmultiply($A, $X);
    print_r($B);

    $C = lpsolve('get_obj_fn', $lp);
    $C = $C[0];
    print_r($C);
    $X = lpsolve('get_variables', $lp);
    $X = $X[0];
    $obj = matrixmultiply($C, $X);
    print_r($obj);

So what we have done here is calculate the values of the constraints (RHS) by multiplying the constraint matrix with the solution vector.
This gives:

    Array
    (
        [0] => Array
            (
                [0] => 0
                [1] => 78.26
                [2] => 0
                [3] => 2.9
            )

        [1] => Array
            (
                [0] => 0.24
                [1] => 0
                [2] => 11.31
                [3] => 0
            )

        [2] => Array
            (
                [0] => 12.68
                [1] => 0
                [2] => 0.08
                [3] => 0.9
            )

    )
    Array
    (
        [0] => 28.6
        [1] => 0
        [2] => 0
        [3] => 31.8275862069
    )
    Array
    (
        [0] => 92.3
        [1] => 6.864
        [2] => 391.292827586
    )
    Array
    (
        [0] => 1
        [1] => 3
        [2] => 6.24
        [3] => 0.0:
    )
    Array
    (
        [0] => 31.7827586207
    )

Now take a look at the values of the constraints that lpsolve has found:

    print_r(lpsolve('get_constraints', $lp));

That gives:

    Array
    (
        [0] => Array
            (
                [0] => 92.3
                [1] => 6.864
                [2] => 391.292827586
            )

        [1] => 1
    )

Exactly the same as the calculated B vector, as expected.

Also the value of the objective is calculated in $obj. What we have done is calculate the value of the objective by multiplying the objective vector with the solution vector. Now take a look at the value of the objective that lpsolve has found:

    print lpsolve('get_objective', $lp);

That gives:

    31.7827586207

Again exactly the same as the calculated obj value, as expected.

### Using string constants

From driver version 5.5.2.14 on, it is possible to use string constants everywhere an lp_solve constant is needed or returned. This is best shown by an example. In the above code we had:

    $lp=lpsolve('make_lp', 0, 4);
    lpsolve('set_verbose', $lp, IMPORTANT);
    lpsolve('add_constraint', $lp, Array(0, 78.26, 0, 2.9), GE, 92.3);
    lpsolve('add_constraint', $lp, Array(0.24, 0, 11.31, 0), LE, 14.8);
    lpsolve('add_constraint', $lp, Array(12.68, 0, 0.08, 0.9), GE, 4);

Note the 3rd parameter on set_verbose and the 4th on add_constraint. These are lp_solve constants. One can define all the possible constants in PHP as is done in the lpsolve driver and then use them in the calls, but that has several disadvantages. First there stays the possibility to provide a constant that is not intended for that particular call. Another issue is that calls that return a constant are still returning it numerical.

Both issues can now be handled by string constants. The above code can be done as following with string constants:

    $lp=lpsolve('make_lp', 0, 4);
    lpsolve('set_verbose', $lp, 'IMPORTANT');
    lpsolve('add_constraint', $lp, Array(0, 78.26, 0, 2.9), 'GE', 92.3);
    lpsolve('add_constraint', $lp, Array(0.24, 0, 11.31, 0), 'LE', 14.8);
    lpsolve('add_constraint', $lp, Array(12.68, 0, 0.08, 0.9), 'GE', 4);

This is not only more readable, there is much lesser chance that mistakes are being made. The calling routine knows which constants are possible and only allows these. So unknown constants or constants that are intended for other calls are not accepted. For example:

    lpsolve('set_verbose', $lp, 'blabla');
    PHP Fatal error:  lpsolve() [<a href='function.lpsolve'>function.lpsolve</a>]:
    BLABLA: Unknown.

    lpsolve('set_verbose', $lp, 'GE');
    PHP Fatal error:  lpsolve() [<a href='function.lpsolve'>function.lpsolve</a>]:
    GE: Not allowed here.

Note the difference between the two error messages. The first says that the constant is not known, the second that the constant cannot be used at that place.

Constants are case insensitive. Internally they are always translated to upper case. Also when returned they will always be in upper case.

The constant names are the ones as specified in the documentation of each API routine. There are only 3 exceptions, extensions actually. 'LE', 'GE' and 'EQ' in add_constraint and is_constr_type can also be '<', '<=', '>', '>=', '='. When returned however, 'GE', 'LE', 'EQ' will be used.

Also in the matrix version of calls, string constants are possible. For example:

    lpsolve('set_constr_type', $lp, Array('LE', 'EQ', 'GE'));

Some constants can be a combination of multiple constants. For example set_scaling:

    lpsolve('set_scaling', $lp, 3+128);

With the string version of constants this can be done as following:

    lpsolve('set_scaling', $lp, 'SCALE_MEAN|SCALE_INTEGERS');

| is the OR operator used to combine multiple constants. There may optinally be spaces before and after the |.

Not all OR combinations are legal. For example in set_scaling, a choice must be made between SCALE_EXTREME, SCALE_RANGE, SCALE_MEAN, SCALE_GEOMETRIC or SCALE_CURTISREID. They may not be combined with each other. This is also tested:

    lpsolve('set_scaling', $lp, 'SCALE_MEAN|SCALE_RANGE');
    PHP Fatal error:  lpsolve() [<a href='function.lpsolve'>function.lpsolve</a>]:
    SCALE_RANGE cannot be combined with SCALE_MEAN

Everywhere constants must be provided, numeric or string values may be provided. The routine automatically interpretes them.

Returning constants is a different story. The user must let lp_solve know how to return it. Numerical or as string. The default is numerical:

    echo lpsolve('get_scaling', $lp);
    131

To let lp_solve return a constant as string, a call to a new function must be made: return_constants

    lpsolve('return_constants', 1);

From now on, all returned constants are returned as string:

    echo lpsolve('get_scaling', $lp);
    SCALE_MEAN|SCALE_INTEGERS

Also when an array of constants is returned, they are returned as string when return_constants is set:

    print_r(lpsolve('get_constr_type', $lp));
    Array
    (
        [0] => LE
        [1] => EQ
        [2] => GE
    )

This for all routines until return_constants is again called with 0:

    lpsolve('return_constants', 0);

The (new) current setting of return_constants is always returned by the call. Even when set:

    echo lpsolve('return_constants', 1);
    1

To get the value without setting it, don't provide the second argument:

    echo lpsolve('return_constants');
    1

In the next part of this documentation, return_constants is the default, 0, so all constants are returned numerical and provided constants are also numerical. This to keep the documentation as compatible as possible with older versions. But don't let you hold that back to use string constants in your code.

### php-files

PHP can execute a sequence of statements stored in diskfiles. Such files are called PHP scripts and should have the file type of ".php" as the last part of their filename (extension).

You can put PHP commands in them and execute them at any time. The PHP script can be executed in the command line via the command php -f script.php. The script files contain plain ascii data. a PHP file can also be included by other PHP code. This via the include command. This way it is possible to define routine in one script and execute it in another. All this can be done via command line or via a webserver.

Note that when used under a webserver like apache that these php files must be in a specific location. For example /var/www

The lpsolve PHP distribution contains some example script to demonstrate this.

#### example1.php

Contains the commands as shown in the first example of this article.

#### example2.php

Contains the commands as shown in the second example of this article.

#### example3.php

Contains the commands of a practical example. See further in this article.

#### example4.php

Contains the commands of a practical example. See further in this article.

#### example5.php

Contains the commands of a practical example. See further in this article.

#### example6.php

Contains the commands of a practical example. See further in this article.

#### lp_solve.php

This script uses the API to create a higher-level function called lp_solve. This function accepts as arguments some matrices and options to create and solve an lp model. The script must first be inserted in the current code via an include command:

    include "lp_solve.php";

Use lp_solve(); to see its usage:

    LP_SOLVE  Solves mixed integer linear programming problems.

       SYNOPSIS: [obj,x,duals] = lp_solve(f,a,b,e,vlb,vub,xint,scalemode,keep)

          solves the MILP problem

                  max v = f'*x
                    a*x <> b
                      vlb <= x <= vub
                      x(int) are integer

       ARGUMENTS: The first four arguments are required:

                f: n vector of coefficients for a linear objective function.
                a: m by n matrix representing linear constraints.
                b: m vector of right sides for the inequality constraints.
                e: m vector that determines the sense of the inequalities:
                          e(i) = -1  ==> Less Than
                          e(i) =  0  ==> Equals
                          e(i) =  1  ==> Greater Than
              vlb: n vector of lower bounds. If empty or omitted,
                   then the lower bounds are set to zero.
              vub: n vector of upper bounds. May be omitted or empty.
             xint: vector of integer variables. May be omitted or empty.
        scalemode: scale flag. Off when 0 or omitted.
             keep: Flag for keeping the lp problem after it's been solved.
                   If omitted, the lp will be deleted when solved.

       OUTPUT: A nonempty output is returned if a solution is found:

              obj: Optimal value of the objective function.
                x: Optimal value of the decision variables.
            duals: solution of the dual problem.

Example of usage. To create and solve following lp-model:

    max: -x1 + 2 x2;
    C1: 2x1 + x2 < 5;
    -4 x1 + 4 x2 <5;

    int x2,x1;

The following command can be used:

    include "lp_solve.php";
    $ret = lp_solve(Array(-1, 2), Array(Array(2, 1), Array(-4, 4)), Array(5, 5), Array(-1, -1), null, null, Array(1, 2));
    print_r($ret);

This gives:

    Array
    (
        [0] => 3
        [1] => Array
            (
                [0] => 1
                [1] => 2
            )

        [2] => Array
            (
                [0] => 0
                [1] => 0
            )

    )

#### lp_maker.php

This script is analog to the lp_solve script and also uses the API to create a higher-level function called lp_maker. This function accepts as arguments some matrices and options to create an lp model. Note that this scripts only creates a model and returns a handle. The script must first be inserted in the current code via an include command:

    include "lp_maker.php";

Use lp_maker(); to see its usage:

    LP_MAKER  Makes mixed integer linear programming problems.

       SYNOPSIS: lp_handle = lp_maker(f,a,b,e,vlb,vub,xint,scalemode,setminim)
          make the MILP problem
            max v = f'*x
              a*x <> b
                vlb <= x <= vub
                x(int) are integer

       ARGUMENTS: The first four arguments are required:
                f: n vector of coefficients for a linear objective function.
                a: m by n matrix representing linear constraints.
                b: m vector of right sides for the inequality constraints.
                e: m vector that determines the sense of the inequalities:
                          e(i) < 0  ==> Less Than
                          e(i) = 0  ==> Equals
                          e(i) > 0  ==> Greater Than
              vlb: n vector of non-negative lower bounds. If empty or omitted,
                   then the lower bounds are set to zero.
              vub: n vector of upper bounds. May be omitted or empty.
             xint: vector of integer variables. May be omitted or empty.
        scalemode: Autoscale flag. Off when 0 or omitted.
         setminim: Set maximum lp when this flag equals 0 or omitted.

       OUTPUT: lp_handle is an integer handle to the lp created.

Example of usage. To create following lp-model:

    max: -x1 + 2 x2;
    C1: 2x1 + x2 < 5;
    -4 x1 + 4 x2 <5;

    int x2,x1;

The following command can be used:

    include "lp_maker.php";
    $lp = lp_maker(Array(-1, 2), Array(Array(2, 1), Array(-4, 4)), Array(5, 5), Array(-1, -1), null, null, Array(1, 2));
    print $lp . "\n";

This gives 0.

To solve the model and get the solution:

    lpsolve('solve', $lp);
    print lpsolve('get_objective', $lp) . "\n";
    $ret = lpsolve('get_variables', $lp);
    print_r($ret);

This gives:

    3
    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 2
            )

        [1] => 1
    )

Don't forget to free the handle and its associated memory when you are done:

    lpsolve('delete_lp', $lp);

#### lpdemo.php

Contains several examples to build and solve lp models.

#### ex.php

Contains several examples to build and solve lp models. Also solves the lp_examples from the lp_solve distribution.

### A practical example

We shall illustrate the method of linear programming by means of a simple example, giving a combination graphical/numerical solution, and then solve both a slightly as well as a substantially more complicated problem.

Suppose a farmer has 75 acres on which to plant two crops: wheat and barley. To produce these crops, it costs the farmer (for seed, fertilizer, etc.) $120 per acre for the wheat and $210 per acre for the barley. The farmer has $15000 available for expenses. But after the harvest, the farmer must store the crops while awaiting favourable market conditions. The farmer has storage space for 4000 bushels. Each acre yields an average of 110 bushels of wheat or 30 bushels of barley. If the net profit per bushel of wheat (after all expenses have been subtracted) is $1.30 and for barley is $2.00, how should the farmer plant the 75 acres to maximize profit?

We begin by formulating the problem mathematically. First we express the objective, that is the profit, and the constraints algebraically, then we graph them, and lastly we arrive at the solution by graphical inspection and a minor arithmetic calculation.

Let x denote the number of acres allotted to wheat and y the number of acres allotted to barley. Then the expression to be maximized, that is the profit, is clearly

P = (110)(1.30)x + (30)(2.00)y = 143x + 60y.

There are three constraint inequalities, specified by the limits on expenses, storage and acreage. They are respectively:

120x + 210y <= 15000
110x + 30y <= 4000
x + y <= 75

Strictly speaking there are two more constraint inequalities forced by the fact that the farmer cannot plant a negative number of acres, namely:

x >= 0, y >= 0.

Next we graph the regions specified by the constraints. The last two say that we only need to consider the first quadrant in the x-y plane. Here's a graph delineating the triangular region in the first quadrant determined by the first inequality.

Now let's put in the other two constraint inequalities.

The black area is the solution space that holds valid solutions. This means that any point in this area fulfils the constraints.

Now let's superimpose on top of this picture a contour plot of the objective function P.

The lines give a picture of the objective function. All solutions that intersect with the black area are valid solutions, meaning that this result also fulfils the set constraints. The more the lines go to the right, the higher the objective value is. The optimal solution or best objective is a line that is still in the black area, but with an as large as possible value.

It seems apparent that the maximum value of P will occur on the level curve (that is, level line) that passes through the vertex of the polygon that lies near (22,53).
It is the intersection of x + y = 75 and 110*x + 30*y = 4000
This is a corner point of the diagram. This is not a coincidence. The simplex algorithm, which is used by lpsolve, starts from a theorem that the optimal solution is such a corner point.
In fact we can compute the result. This is done here with an undefined function matrixinverse which is not available in PHP:

    $x = matrixmultiply(inverse(Array(Array(1, 1), Array(110, 30))), array(75, 4000));
    print_r($x);

With inverse(Array(Array(1, 1), Array(110, 30))) = Array(Array(-0.375, 0.0125), Array(1.375, -0.0125)) that is:

    $x = matrixmultiply(Array(Array(-0.375, 0.0125), Array(1.375, -0.0125)), array(75, 4000));
    print_r($x);

That gives:

    Array
    (
        [0] => 21.875
        [1] => 53.125
    )

The acreage that results in the maximum profit is 21.875 for wheat and 53.125 for barley. In that case the profit is:

    $P = matrixmultiply(Array(143, 60), $x);
    print_r($P);

That gives:

    Array
    (
        [0] => 6315.625
    )

That is, $6315.625.

Note that these command are in script example3.php

Now, lp_solve comes into the picture to solve this linear programming problem more generally. After that we will use it to solve two more complicated problems involving more variables and constraints.

For this example, we use the higher-level script lp_maker to build the model and then some lp_solve API calls to retrieve the solution. Here is again the usage of lp_maker:

     LP_MAKER  Makes mixed integer linear programming problems.

       SYNOPSIS: lp_handle = lp_maker(f,a,b,e,vlb,vub,xint,scalemode,setminim)
          make the MILP problem
            max v = f'*x
              a*x <> b
                vlb <= x <= vub
                x(int) are integer

       ARGUMENTS: The first four arguments are required:
                f: n vector of coefficients for a linear objective function.
                a: m by n matrix representing linear constraints.
                b: m vector of right sides for the inequality constraints.
                e: m vector that determines the sense of the inequalities:
                          e(i) < 0  ==> Less Than
                          e(i) = 0  ==> Equals
                          e(i) > 0  ==> Greater Than
              vlb: n vector of non-negative lower bounds. If empty or omitted,
                   then the lower bounds are set to zero.
              vub: n vector of upper bounds. May be omitted or empty.
             xint: vector of integer variables. May be omitted or empty.
        scalemode: Autoscale flag. Off when 0 or omitted.
         setminim: Set maximum lp when this flag equals 0 or omitted.

       OUTPUT: lp_handle is an integer handle to the lp created.

Now let's formulate this model with lp_solve:

    include "lp_maker.php";
    $f = Array(143, 60);
    $A = Array(Array(120, 210), Array(110, 30), Array(1, 1));
    $b = Array(15000, 4000, 75);
    $lp = lp_maker($f, $A, $b, Array(-1, -1, -1), null, null, null, 1, 0);
    $solvestat = lpsolve('solve', $lp);
    $obj = lpsolve('get_objective', $lp);
    print $obj . "\n";
    $x = lpsolve('get_variables', $lp);
    print_r($x);
    lpsolve('delete_lp', $lp);

That gives:

    6315.625
    Array
    (
        [0] => Array
            (
                [0] => 21.875
                [1] => 53.125
            )

        [1] => 1
    )

Note that these command are in script example4.php

With the higher-level script lp_maker, we provide all data to lp_solve. lp_solve returns a handle (lp) to the created model. Then the API call 'solve' is used to calculate the optimal solution of the model. The value of the objective function is retrieved via the API call 'get_objective' and the values of the variables are retrieved via the API call 'get_variables'. At last, the model is removed from memory via a call to 'delete_lp'. Don't forget this to free all memory allocated by lp_solve.

The solution is the same answer we obtained before. Note that the non-negativity constraints are accounted implicitly because variables are by default non-negative in lp_solve.

Well, we could have done this problem by hand (as shown in the introduction) because it is very small and it can be graphically presented.
Now suppose that the farmer is dealing with a third crop, say corn, and that the corresponding data is:

> cost per acre | $150.75
> yield per acre | 125 bushels
> profit per bushel | $1.56

With three variables it is already a lot more difficult to show this model graphically. Adding more variables makes it even impossible because we can't imagine anymore how to represent this. We only have a practical understanding of 3 dimensions, but beyond that it is all very theoretical.

If we denote the number of acres allotted to corn by z, then the objective function becomes:

P = (110)(1.30)x + (30)(2.00)y + (125)(1.56) = 143x + 60y + 195z

And the constraint inequalities are:

120x + 210y + 150.75z <= 15000
110x + 30y + 125z <= 4000
x + y + z <= 75
x >= 0, y >= 0, z >= 0

The problem is solved with lp_solve as follows:

    include("lp_maker.php");

    $f = Array(143, 60, 195);
    $A = Array(Array(120, 210, 150.75), Array(110, 30, 125), Array(1, 1, 1));
    $b = Array(15000, 4000, 75);
    $lp = lp_maker($f, $A, $b, Array(-1, -1, -1), null, null, null, 1, 0);
    $solvestat = lpsolve('solve', $lp);
    $obj = lpsolve('get_objective', $lp);
    print $obj . "\n";
    $x = lpsolve('get_variables', $lp);
    print_r($x);
    lpsolve('delete_lp', $lp);

That gives:

    6986.84210526
    Array
    (
        [0] => Array
            (
                [0] => 0
                [1] => 56.5789473684
                [2] => 18.4210526316
            )

        [1] => 1
    )

Note that these command are in script example5.php

So the farmer should ditch the wheat and plant 56.5789 acres of barley and 18.4211 acres of corn.

There is no practical limit on the number of variables and constraints that PHP can handle. Certainly none that the relatively unsophisticated user will encounter. Indeed, in many true applications of the technique of linear programming, one needs to deal with many variables and constraints. The solution of such a problem by hand is not feasible, and software like PHP is crucial to success. For example, in the farming problem with which we have been working, one could have more crops than two or three. Think agribusiness instead of family farmer. And one could have constraints that arise from other things beside expenses, storage and acreage limitations. For example:

- Availability of seed. This might lead to constraint inequalities like xj < k.
- Personal preferences. Thus the farmer's spouse might have a preference for one variety over another and insist on a corresponding planting, or something similar with a collection of crops; thus constraint inequalities like xi < xj or x1 + x2 > x3.
- Government subsidies. It may take a moment's reflection on the reader's part, but this could lead to inequalities like xj > k.

Below is a sequence of commands that solves exactly such a problem. You should be able to recognize the objective expression and the constraints from the data that is entered. But as an aid, you might answer the following questions:

- How many crops are under consideration?
- What are the corresponding expenses? How much is available for expenses?
- What are the yields in each case? What is the storage capacity?
- How many acres are available?
- What crops are constrained by seed limitations? To what extent?
- What about preferences?
- What are the minimum acreages for each crop?

    include("lp_maker.php");

    $f = Array(110*1.3, 30*2.0, 125*1.56, 75*1.8, 95*.95, 100*2.25, 50*1.35);
    $A = Array(Array(120, 210, 150.75, 115, 186, 140, 85), Array(110, 30, 125, 75, 95, 100, 50), Array(1, 1, 1, 1, 1, 1, 1), Array(1, -1, 0, 0, 0, 0, 0), Array(0, 0, 1, 0, -2, 0, 0), Array(0, 0, 0, -1, 0, -1, 1));
    $b = Array(55000, 40000, 400, 0, 0, 0);
    $lp = lp_maker($f, $A, $b, Array(-1, -1, -1, -1, -1, -1), Array(10, 10, 10, 10, 20, 20, 20), Array(100, Infinite, 50, Infinite, Infinite, 250, Infinite), null, 1, 0);
    $solvestat = lpsolve('solve', $lp);
    $obj = lpsolve('get_objective', $lp);
    print $obj . "\n";
    $x = lpsolve('get_variables', $lp);
    print_r($x);
    lpsolve('delete_lp', $lp);

That gives:

    75398.0434783
    Array
    (
        [0] => Array
            (
                [0] => 10
                [1] => 10
                [2] => 40
                [3] => 45.652173913
                [4] => 20
                [5] => 250
                [6] => 20
            )

        [1] => 1
    )

Note that these command are in script example6.php

Note that we have used in this formulation the vlb and vub arguments of lp_maker. This to set lower and upper bounds on variables. This could have been done via extra constraints, but it is more performant to set bounds on variables. Also note that Infinity is used for variables that have no upper limit.

Note that despite the complexity of the problem, lp_solve solves it almost instantaneously. It seems the farmer should bet the farm on crop number 6. We strongly suggest you alter the expense and/or the storage limit in the problem and see what effect that has on the answer.

### Another, more theoretical, example

Suppose we want to solve the following linear program using PHP:

max 4x1 + 2x2 + x3
s. t. 2x1 + x2 <= 1
x1 + 2x3 <= 2
x1 + x2 + x3 = 1
x1 >= 0
x1 <= 1
x2 >= 0
x2 <= 1
x3 >= 0
x3 <= 2

Convert the LP into PHP format we get:

$f = Array(4, 2, 1);
$A = Array(Array(2, 1, 0), Array(1, 0, 2), Array(1, 1, 1));
$b = Array(1, 2, 1);

Note that constraints on single variables are not put in the constraint matrix. lp_solve can set bounds on individual variables and this is more performant than creating additional constraints. These bounds are:

$l = Array( 0, 0, 0);
$u = Array( 1, 1, 2);

Now lets enter this in PHP:

    $f = Array(4, 2, 1);
    $A = Array(Array(2, 1, 0), Array(1, 0, 2), Array(1, 1, 1));
    $b = Array(1, 2, 1);
    $l = Array( 0, 0, 0);
    $u = Array( 1, 1, 2);

Now solve the linear program using PHP: Use the commands

    include "lp_maker.php";
    $lp = lp_maker($f, $A, $b, Array(-1, -1, -1), $l, $u, null, 1, 0);
    $solvestat = lpsolve('solve', $lp);
    $obj = lpsolve('get_objective', $lp);
    print $obj . "\n";
    $x = lpsolve('get_variables', $lp);
    print_r($x);
    lpsolve('delete_lp', $lp);

This gives:

    2.5
    Array
    (
        [0] => Array
            (
                [0] => 0.5
                [1] => 0
                [2] => 0.5
            )

        [1] => 1
    )

What to do when some of the variables are missing ?
For example, suppose there are no lower bounds on the variables. In this case define l to be the empty set using the PHP command:

    l = null

This has the same effect as before, because lp_solve has as default lower bound for variables 0.

But what if you want that variables may also become negative?
Then you can use -Infinite as lower bounds:

    $l = Array(-Infinite, -Infinite, -Infinite);

Solve this and you get a different result:

    include "lp_maker.php";
    $lp = lp_maker($f, $A, $b, Array(-1, -1, -1), $l, $u, null, 1, 0);
    $solvestat = lpsolve('solve', $lp);
    $obj = lpsolve('get_objective', $lp);
    print $obj . "\n";
    $x = lpsolve('get_variables', $lp);
    print_r($x);
    lpsolve('delete_lp', $lp);

This gives:

    2.66666666667
    Array
    (
        [0] => Array
            (
                [0] => 0.666666666667
                [1] => -0.333333333333
                [2] => 0.666666666667
            )

        [1] => 1
    )

### Overview of API routines

Note that everwhere where lp is used as argument that this can be a handle (lp) or the models name.

- add_column, add_columnex
  - return = lpsolve('add_column', lp, [column])
  - return = lpsolve('add_columnex', lp, [column])
  - Both have the same interface from add_column but act as add_columnex
- add_constraint, add_constraintex
  - return = lpsolve('add_constraint', lp, [row], constr_type, rh)
  - return = lpsolve('add_constraintex', lp, [row], constr_type, rh)
  - Both have the same interface from add_constraint but act as add_constraintex
- add_SOS
  - return = lpsolve('add_SOS', lp, name, sostype, priority, [sosvars], [weights])
  - The count argument in the API documentation is not needed in PHP since the number of elements is derived from the size of the sosvars and weights matrices. These must have the same size.
- column_in_lp
  - return = lpsolve('column_in_lp', lp, [column])
  - No special considerations.
- copy_lp
  - lp_handle = lpsolve('copy_lp', lp)
  - No special considerations.
- default_basis
  - lpsolve('default_basis', lp)
  - No special considerations.
- del_column
  - return = lpsolve('del_column', lp, column)
  - No special considerations.
- del_constraint
  - return = lpsolve('del_constraint', lp, del_row)
  - No special considerations.
- delete_lp
  - lpsolve('delete_lp', lp)
  - No special considerations.
- free_lp
  - lpsolve('free_lp', lp)
  - lp is not changed as in the lpsolve API since it is a read_only input parameter. So it acts the same as delete_lp.
- get_anti_degen
  - return = lpsolve('get_anti_degen', lp)
  - No special considerations.
- get_basis
  - [bascolumn] = lpsolve('get_basis', lp {, nonbasic})
  - The bascolumn argument in the API documentation is here the return value. The nonbasic argument is optional in PHP. If not provided, then 0 is used.
- get_basiscrash
  - return = lpsolve('get_basiscrash', lp)
  - No special considerations.
- get_bb_depthlimit
  - return = lpsolve('get_bb_depthlimit', lp)
  - No special considerations.
- get_bb_floorfirst
  - return = lpsolve('get_bb_floorfirst', lp)
  - No special considerations.
- get_bb_rule
  - return = lpsolve('get_bb_rule', lp)
  - No special considerations.
- get_bounds_tighter
  - return = lpsolve('get_bounds_tighter', lp)
  - No special considerations.
- get_break_at_value
  - return = lpsolve('get_break_at_value', lp)
  - No special considerations.
- get_col_name
  - name = lpsolve('get_col_name', lp, column)
  - [names] = lpsolve('get_col_name', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_column get_columnex
  - [column, return] = lpsolve('get_column', lp, col_nr)
  - [column, return] = lpsolve('get_columnex', lp, col_nr)
  - The column argument in the API documentation is here the first return value.
  - The return code of the call is the second return value.
- get_constr_type
  - return = lpsolve('get_constr_type', lp, row)
  - [constr_type] = lpsolve('get_constr_type', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_constr_value
  - return = lpsolve('get_constr_value', lp, row {, primsolution})
  - The primsolution argument is optional. If not provided, then the solution of last solve is used.
- get_constraints
  - [constr, return] = lpsolve('get_constraints', lp)
  - The constr argument in the API documentation is here the first return value.
  - The return code of the call is the second return value.
- get_dual_solution
  - [duals, return] = lpsolve('get_dual_solution', lp)
  - The duals argument in the API documentation is here the first return value.
  - In the API, element 0 is not used and values start from element 1. In PHP, there is no unused element in the matrix.
  - The return code of the call is the second return value.
- get_epsb
  - return = lpsolve('get_epsb', lp)
  - No special considerations.
- get_epsd
  - return = lpsolve('get_epsd', lp)
  - No special considerations.
- get_epsel
  - return = lpsolve('get_epsel', lp)
  - No special considerations.
- get_epsint
  - return = lpsolve('get_epsint', lp)
  - No special considerations.
- get_epsperturb
  - return = lpsolve('get_epsperturb', lp)
  - No special considerations.
- get_epspivot
  - return = lpsolve('get_epspivot', lp)
  - No special considerations.
- get_improve
  - return = lpsolve('get_improve', lp)
  - No special considerations.
- get_infinite
  - return = lpsolve('get_infinite', lp)
  - No special considerations.
- get_lowbo
  - return = lpsolve('get_lowbo', lp, column)
  - [return] = lpsolve('get_lowbo', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_lp_index
  - return = lpsolve('get_lp_index', lp, orig_index)
  - No special considerations.
- get_lp_name
  - name = lpsolve('get_lp_name', lp)
  - No special considerations.
- get_mat
  - value = lpsolve('get_mat', lp, row, col)
  - [matrix, return] = lpsolve('get_mat', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix in the first return value. The return code of the call is the second return value.
- get_max_level
  - return = lpsolve('get_max_level', lp)
  - No special considerations.
- get_maxpivot
  - return = lpsolve('get_maxpivot', lp)
  - No special considerations.
- get_mip_gap
  - return = lpsolve('get_mip_gap', lp, absolute)
  - No special considerations.
- get_nameindex
  - return = lpsolve('get_nameindex', lp, name, isrow)
  - No special considerations.
- get_Ncolumns
  - return = lpsolve('get_Ncolumns', lp)
  - No special considerations.
- get_negrange
  - return = lpsolve('get_negrange', lp)
  - No special considerations.
- get_nonzeros
  - return = lpsolve('get_nonzeros', lp)
  - No special considerations.
- get_Norig_columns
  - return = lpsolve('get_Norig_columns', lp)
  - No special considerations.
- get_Norig_rows
  - return = lpsolve('get_Norig_rows', lp)
  - No special considerations.
- get_Nrows
  - return = lpsolve('get_Nrows', lp)
  - No special considerations.
- get_obj_bound
  - return = lpsolve('get_obj_bound', lp)
  - No special considerations.
- get_objective
  - return = lpsolve('get_objective', lp)
  - No special considerations.
- get_orig_index
  - return = lpsolve('get_orig_index', lp, lp_index)
  - No special considerations.
- get_origcol_name
  - name = lpsolve('get_origcol_name', lp, column)
  - [names] = lpsolve('get_origcol_name', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_origrow_name
  - name = lpsolve('get_origrow_name', lp, row)
  - [names] = lpsolve('get_origrow_name', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_pivoting
  - return = lpsolve('get_pivoting', lp)
  - No special considerations.
- get_presolve
  - return = lpsolve('get_presolve', lp)
  - No special considerations.
- get_presolveloops
  - return = lpsolve('get_presolveloops', lp)
  - No special considerations.
- get_primal_solution
  - [pv, return] = lpsolve('get_primal_solution', lp)
  - The pv argument in the API documentation is here the first return value.
  - The return code of the call is the second return value.
- get_print_sol
  - return = lpsolve('get_print_sol', lp)
  - No special considerations.
- get_ptr_constraints
  - Not implemented.
- get_ptr_dualsolution
  - Not implemented.
- get_ptr_primal_solution
  - Not implemented.
- get_ptr_sensitivity_obj, get_ptr_sensitivity_objex
  - Not implemented.
- get_ptr_sensitivity_rhs
  - Not implemented.
- get_ptr_variables
  - Not implemented.
- get_rh
  - return = lpsolve('get_rh', lp, row)
  - [rh] = lpsolve('get_rh', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_rh_range
  - return = lpsolve('get_rh_range', lp, row)
  - [rh_ranges] = lpsolve('get_rh_range', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_row get_rowex
  - [row, return] = lpsolve('get_row', lp, row_nr)
  - [row, return] = lpsolve('get_rowex', lp, row_nr)
  - The row argument in the API documentation is here the first return value.
  - In the API, element 0 is not used and values start from element 1. In PHP, there is no unused element in the matrix.
  - The return code of the call is the second return value.
- get_row_name
  - name = lpsolve('get_row_name', lp, row)
  - [names] = lpsolve('get_row_name', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_scalelimit
  - return = lpsolve('get_scalelimit', lp)
  - No special considerations.
- get_scaling
  - return = lpsolve('get_scaling', lp)
  - No special considerations.
- get_sensitivity_obj, get_sensitivity_objex
  - [objfrom, objtill, objfromvalue, objtillvalue, return] = lpsolve('get_sensitivity_obj', lp)
  - [objfrom, objtill, objfromvalue, objtillvalue, return] = lpsolve('get_sensitivity_objex', lp)
  - The objfrom, objtill, objfromvalue, objtillvalue arguments in the API documentation are here the return values. Note that PHP allows the return of fewer variables. For example if only objfrom and objtill are needed then the call can be [objfrom, objtill] = lpsolve('get_sensitivity_obj', lp). The unrequested values are even not calculated.
  - Since the API routine doesn't calculate the objtillvalue value at this time, PHP always returns a zero vector for this.
  - The return code of the call is the last value.
  - get_sensitivity_obj and get_sensitivity_objex are both implemented, but have the same functionality.
- get_sensitivity_rhs, get_sensitivity_rhsex
  - [duals, dualsfrom, dualstill, return] = lpsolve('get_sensitivity_rhs', lp)
  - [duals, dualsfrom, dualstill, return] = lpsolve('get_sensitivity_rhsex', lp)
  - The duals, dualsfrom, dualstill arguments in the API documentation are here the return values. Note that PHP allows the return of fewer variables. For example if only duals is needed then the call can be [duals] = lpsolve('get_sensitivity_rhs', lp). The unrequested values are even not calculated.
  - The return code of the call is the last value.
  - get_sensitivity_rhs and get_sensitivity_rhsex are both implemented, but have the same functionality.
- get_simplextype
  - return = lpsolve('get_simplextype', lp)
  - No special considerations.
- get_solutioncount
  - return = lpsolve('get_solutioncount', lp)
  - No special considerations.
- get_solutionlimit
  - return = lpsolve('get_solutionlimit', lp)
  - No special considerations.
- get_status
  - return = lpsolve('get_status', lp)
  - No special considerations.
- get_statustext
  - return = lpsolve('get_statustext', lp, statuscode)
  - No special considerations.
- get_timeout
  - return = lpsolve('get_timeout', lp)
  - No special considerations.
- get_total_iter
  - return = lpsolve('get_total_iter', lp)
  - No special considerations.
- get_total_nodes
  - return = lpsolve('get_total_nodes', lp)
  - No special considerations.
- get_upbo
  - return = lpsolve('get_upbo', lp, column)
  - [upbo] = lpsolve('get_upbo', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_var_branch
  - return = lpsolve('get_var_branch', lp, column)
  - [var_branch] = lpsolve('get_var_branch', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_var_dualresult
  - return = lpsolve('get_var_dualresult', lp, index)
  - No special considerations.
- get_var_primalresult
  - return = lpsolve('get_var_primalresult', lp, index)
  - No special considerations.
- get_var_priority
  - return = lpsolve('get_var_priority', lp, column)
  - [var_priority] = lpsolve('get_var_priority', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- get_variables
  - [var, return] = lpsolve('get_variables', lp)
  - The var argument in the API documentation is here the first return value.
  - The return code of the call is the second return value.
- get_verbose
  - return = lpsolve('get_verbose', lp)
  - No special considerations.
- get_working_objective
  - return = lpsolve('get_working_objective', lp)
  - No special considerations.
- guess_basis
  - [basisvector, return] = lpsolve('guess_basis', lp, [guessvector])
  - In the API, element 0 of guessvector is not used and values start from element 1. In PHP, there is no unused element in the matrix.
  - In the API, element 0 of basisvector is not used and values start from element 1. In PHP, there is no unused element in the matrix.
- has_BFP
  - return = lpsolve('has_BFP', lp)
  - No special considerations.
- has_XLI
  - return = lpsolve('has_XLI', lp)
  - No special considerations.
- is_add_rowmode
  - return = lpsolve('is_add_rowmode', lp)
  - No special considerations.
- is_anti_degen
  - return = lpsolve('is_anti_degen', lp, testmask)
  - No special considerations.
- is_binary
  - return = lpsolve('is_binary', lp, column)
  - [binary] = lpsolve('is_binary', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- is_break_at_first
  - return = lpsolve('is_break_at_first', lp)
  - No special considerations.
- is_constr_type
  - return = lpsolve('is_constr_type', lp, row, mask)
  - No special considerations.
- is_debug
  - return = lpsolve('is_debug', lp)
  - No special considerations.
- is_feasible
  - return = lpsolve('is_feasible', lp, [values] {, threshold})
  - The threshold argument is optional. When not provided, the value of get_epsint will be taken.
- is_free is_unbounded
  - return = lpsolve('is_free', lp, column)
  - return = lpsolve('is_unbounded', lp, column)
  - [free] = lpsolve('is_free', lp)
  - [free] = lpsolve('is_unbounded', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- is_infinite
  - return = lpsolve('is_infinite', lp, value)
  - No special considerations.
- is_int
  - return = lpsolve('is_int', lp, column)
  - [int] = lpsolve('is_int', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- is_integerscaling
  - return = lpsolve('is_integerscaling', lp)
  - No special considerations.
- is_maxim
  - return = lpsolve('is_maxim', lp)
  - No special considerations.
- is_nativeBFP
  - return = lpsolve('is_nativeBFP', lp)
  - No special considerations.
- is_nativeXLI
  - return = lpsolve('is_nativeXLI', lp)
  - No special considerations.
- is_negative
  - return = lpsolve('is_negative', lp, column)
  - [negative] = lpsolve('is_negative', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- is_piv_mode
  - return = lpsolve('is_piv_mode', lp, testmask)
  - No special considerations.
- is_piv_rule
  - return = lpsolve('is_piv_rule', lp, rule)
  - No special considerations.
- is_presolve
  - return = lpsolve('is_presolve', lp, testmask)
  - No special considerations.
- is_scalemode
  - return = lpsolve('is_scalemode', lp, testmask)
  - No special considerations.
- is_scaletype
  - return = lpsolve('is_scaletype', lp, scaletype)
  - No special considerations.
- is_semicont
  - return = lpsolve('is_semicont', lp, column)
  - [semicont] = lpsolve('is_semicont', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- is_SOS_var
  - return = lpsolve('is_SOS_var', lp, column)
  - [SOS_var] = lpsolve('is_SOS_var', lp)
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows retrieving the values into a PHP matrix.
- is_trace
  - return = lpsolve('is_trace', lp)
  - No special considerations.
- is_use_names
  - return = lpsolve('is_use_names', lp, isrow)
  - No special considerations.
- lp_solve_version
  - versionstring = lpsolve('lp_solve_version')
  - The lpsolve API routine returns the version information in 4 provided argument variables while the PHP version returns the information as a string in the format major.minor.release.build
- make_lp
  - lp_handle = lpsolve('make_lp', rows, columns)
  - lp_handle is not a pointer to an lprec structure as in the API, but an incrementing handle number starting from 0.
- print_constraints
  - lpsolve('print_constraints', lp {, columns})
  - columns is optional. If not specified, then 1 is used.
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
  - The same information can also be obtained via lpsolve('get_constraints', lp). This shows the result on screen.
- print_debugdump
  - return = lpsolve('print_debugdump', lp, filename)
  - No special considerations.
- print_duals
  - lpsolve('print_duals', lp)
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
  - The same information can be obtained via lpsolve('get_dual_solution', lp). This shows the result on screen.
- print_lp
  - lpsolve('print_lp', lp)
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
- print_objective
  - lpsolve('print_objective', lp)
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
  - The same information can be obtained via lpsolve('get_objective', lp). This shows the result on screen.
- print_scales
  - lpsolve('print_scales', lp)
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
- print_solution
  - lpsolve('print_solution', lp {, columns})
  - columns is optional. If not specified, then 1 is used.
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
  - The same information can also be obtained via lpsolve('get_variables', lp). This shows the result on screen.
- print_str
  - lpsolve('print_str', lp, str)
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
- print_tableau
  - lpsolve('print_tableau', lp)
  - First call set_outputfile to specify where the information is written to. In the API documentation it is written that by default, the output goes to stdout, but under PHP (Windows) this means that the output is not shown.
- put_abortfunc
  - Not implemented.
- put_logfunc
  - Not implemented.
  - However, the lpsolve driver sets a log function to redirect the output of lpsolve from stdout (which is not visible in Windows PHP) to the command window of PHP. As such, all reported output can be seen in PHP. How much output is seen is controlled by the verbose level that can be defined by set_verbose or can be specified in the read_ routines.
- put_msgfunc
  - Not implemented.
- read_basis
  - [ret, info] = lpsolve('read_basis', lp, filename)
  - No special considerations.
- read_freemps, read_freeMPS
  - lp_handle = lpsolve('read_freemps', filename {, options})
  - lp_handle = lpsolve('read_freeMPS', filename {, options})
  - In the lpsolve API, read_freemps needs a FILE handle. In PHP it needs the filename and thus acts the same as read_freeMPS.
  - lp_handle is not a pointer to an lprec structure as in the API, but an incrementing handle number starting from 0.
  - options is optional. If not specified, then NORMAL is used.
- read_lp, read_LP
  - lp_handle = lpsolve('read_lp', filename {, verbose {, lp_name}})
  - lp_handle = lpsolve('read_LP', filename {, verbose {, lp_name}})
  - In the lpsolve API, read_lp needs a FILE handle. In PHP it needs the filename and thus acts the same as read_LP.
  - lp_handle is not a pointer to an lprec structure as in the API, but an incrementing handle number starting from 0.
  - verbose is optional. If not provided then NORMAL is used.
  - lp_name is optional. If not provided then no name is given to the model ('').
- read_mps, read_MPS
  - lp_handle = lpsolve('read_mps', filename {, options})
  - lp_handle = lpsolve('read_MPS', filename {, options})
  - In the lpsolve API, read_mps needs a FILE handle. In PHP it needs the filename and thus acts the same as read_MPS.
  - lp_handle is not a pointer to an lprec structure as in the API, but an incrementing handle number starting from 0.
  - options is optional. If not specified, then NORMAL is used.
- read_params
  - return = lpsolve('read_params', lp, filename {, options })
  - options is optional.
- read_XLI
  - lp_handle = lpsolve('read_XLI', xliname, modelname {, dataname {, options {, verbose}}}
  - lp_handle is not a pointer to an lprec structure as in the API, but an incrementing handle number starting from 0.
  - dataname is optional. When not provided, '' (NULL) is taken. '' is taken as NULL.
  - options is optional. When not provided, '' is taken.
  - verbose is optional. If not specified, then NORMAL is used.
- reset_basis
  - Not implemented.
  - Use default_basis
- set_basisvar
  - lpsolve('set_basisvar', lp, basisPos, enteringCol)
  - No special considerations.
- set_add_rowmode
  - return = lpsolve('set_add_rowmode', lp, turnon)
  - No special considerations.
- set_anti_degen
  - lpsolve('set_anti_degen', lp, anti_degen)
  - No special considerations.
- set_basis
  - return = lpsolve('set_basis', lp, [bascolumn], nonbasic)
  - In the API, element 0 of bascolumn is not used and values start from element 1. In PHP, there is no unused element in the matrix.
- set_basiscrash
  - lpsolve('set_basiscrash', lp, mode)
  - No special considerations.
- set_bb_depthlimit
  - lpsolve('set_bb_depthlimit', lp, bb_maxlevel)
  - No special considerations.
- set_bb_floorfirst
  - lpsolve('set_bb_floorfirst', lp, bb_floorfirst)
  - No special considerations.
- set_bb_rule
  - lpsolve('set_bb_rule', lp, bb_rule)
  - No special considerations.
- set_BFP
  - return = lpsolve('set_BFP', lp, filename)
  - No special considerations.
- set_binary
  - return = lpsolve('set_binary', lp, column, must_be_bin)
  - return = lpsolve('set_binary', lp, [must_be_bin])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_bounds
  - return = lpsolve('set_bounds', lp, column, lower, upper)
  - return = lpsolve('set_bounds', lp, [lower], [upper])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_bounds_tighter
  - lpsolve('set_bounds_tighter', lp, tighten)
  - No special considerations.
- set_break_at_first
  - lpsolve('set_break_at_first', lp, break_at_first)
  - No special considerations.
- set_break_at_value
  - lpsolve('set_break_at_value', lp, break_at_value)
  - No special considerations.
- set_col_name
  - return = lpsolve('set_col_name', lp, column, name)
  - return = lpsolve('set_col_name', lp, [names])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_column, set_columnex
  - return = lpsolve('set_column', lp, col_no, [column])
  - return = lpsolve('set_columnex', lp, col_no, [column])
  - Both have the same interface from set_column but act as set_columnex
- set_constr_type
  - return = lpsolve('set_constr_type', lp, row, con_type)
  - return = lpsolve('set_constr_type', lp, [con_type])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all rows.
- set_debug
  - lpsolve('set_debug', lp, debug)
  - No special considerations.
- set_epsb
  - lpsolve('set_epsb', lp, epsb)
  - No special considerations.
- set_epsd
  - lpsolve('set_epsd', lp, epsd)
  - No special considerations.
- set_epsel
  - lpsolve('set_epsel', lp, epsel)
  - No special considerations.
- set_epsint
  - lpsolve('set_epsint', lp, epsint)
  - No special considerations.
- set_epslevel
  - lpsolve('set_epslevel', lp, epslevel)
  - No special considerations.
- set_epsperturb
  - lpsolve('set_epsperturb', lp, epsperturb)
  - No special considerations.
- set_epspivot
  - lpsolve('set_epspivot', lp, epspivot)
  - No special considerations.
- set_free set_unbounded
  - return = lpsolve('set_free', lp, column)
  - return = lpsolve('set_unbounded', lp, column)
  - No special considerations.
- set_improve
  - lpsolve('set_improve', lp, improve)
  - No special considerations.
- set_infinite
  - lpsolve('set_infinite', lp, infinite)
  - No special considerations.
- set_int
  - return = lpsolve('set_int', lp, column, must_be_int)
  - return = lpsolve('set_int', lp, [must_be_int])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_lowbo
  - return = lpsolve('set_lowbo', lp, column, value)
  - return = lpsolve('set_lowbo', lp, [values])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_lp_name
  - return = lpsolve('set_lp_name', lp, name)
  - In PHP, when you name a model, this name can be used everywhere where lp is specified. This to access the model via the name instead of via a handle.
- set_mat
  - return = lpsolve('set_mat', lp, row, column, value)
  - return = lpsolve('set_mat', lp, [matrix])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows to set the whole matrix (all rows/columns) at once. This is the most performant way to provide the constraint matrix. Consider using a PHP sparse matrix for maximum performance and least memory usage. The matrix must be two-dimensional.
- set_maxim
  - lpsolve('set_maxim', lp)
  - No special considerations.
- set_maxpivot
  - lpsolve('set_maxpivot', max_num_inv)
  - No special considerations.
- set_minim
  - lpsolve('set_minim', lp)
  - No special considerations.
- set_mip_gap
  - lpsolve('set_mip_gap', lp, absolute, mip_gap)
  - No special considerations.
- set_negrange
  - lpsolve('set_negrange', negrange)
  - No special considerations.
- set_obj
  - return = lpsolve('set_obj', lp, column, value)
  - return = lpsolve('set_obj', lp, [values])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables. It is then the same as set_obj_fn
- set_obj_bound
  - lpsolve('set_obj_bound', lp, obj_bound)
  - No special considerations.
- set_obj_fn, set_obj_fnex
  - return = lpsolve('set_obj_fn', lp, [row])
  - return = lpsolve('set_obj_fnex', lp, [row])
  - Both have the same interface from set_obj_fn but act as set_obj_fnex
  - In the API, element 0 is not used and values start from element 1. In PHP, there is no unused element in the matrix.
- set_outputfile
  - return = lpsolve('set_outputfile', lp, filename)
  - In the API description it says that setting filename to NULL results in writing output back to stdout. In PHP under Windows, output to stdout it not shown. However it results in closing the file. Use '' to have the effect of NULL.
- set_outputstream
  - Not implemented.
- set_pivoting
  - lpsolve('set_pivoting', lp, pivoting)
  - No special considerations.
- set_preferdual
  - lpsolve('set_preferdual', lp, dodual)
  - No special considerations.
- set_presolve
  - lpsolve('set_presolve', lp, do_presolve {, maxloops})
  - The maxloops argument is optional in PHP. If not provided, then infinite is used.
- set_print_sol
  - lpsolve('set_print_sol', lp, print_sol)
  - No special considerations.
- set_rh
  - return = lpsolve('set_rh', lp, row, value)
  - return = lpsolve('set_rh', lp, [values])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all rows. Note that in this case, the value of row 0 is not specified in the matrix.
- set_rh_range
  - return = lpsolve('set_rh_range', lp, row, deltavalue)
  - return = lpsolve('set_rh_range', lp, [deltavalues])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all rows.
- set_rh_vec
  - lpsolve('set_rh_vec', lp, [rh])
  - In the API, element 0 is not used and values start from element 1. In PHP, there is no unused element in the matrix.
- set_row, set_rowex
  - return = lpsolve('set_row', lp, row_no, [row])
  - return = lpsolve('set_rowex', lp, row_no, [row])
  - Both have the same interface from set_row but act as set_rowex
  - In the API, element 0 is not used and values start from element 1. In PHP, there is no unused element in the matrix.
- set_row_name
  - return = lpsolve('set_row_name', lp, row, name)
  - return = lpsolve('set_row_name', lp, [names])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all rows.
- set_scalelimit
  - lpsolve('set_scalelimit', lp, scalelimit)
  - No special considerations.
- set_scaling
  - lpsolve('set_scaling', lp, scalemode)
  - No special considerations.
- set_semicont
  - return = lpsolve('set_semicont', lp, column, must_be_sc)
  - return = lpsolve('set_semicont', lp, [must_be_sc])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_sense
  - lpsolve('set_sense', lp, maximize)
  - No special considerations.
- set_simplextype
  - lpsolve('set_simplextype', lp, simplextype)
  - No special considerations.
- set_solutionlimit
  - lpsolve('set_solutionlimit', lp, simplextype)
  - No special considerations.
- set_timeout
  - lpsolve('set_timeout', lp, sectimeout)
  - No special considerations.
- set_trace
  - lpsolve('set_trace', lp, trace)
  - No special considerations.
- set_upbo
  - return = lpsolve('set_upbo', lp, column, value)
  - return = lpsolve('set_upbo', lp, [values])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_use_names
  - lpsolve('set_use_names', lp, isrow, use_names)
  - No special considerations.
- set_var_branch
  - return = lpsolve('set_var_branch', lp, column, branch_mode)
  - return = lpsolve('set_var_branch', lp, [branch_mode])
  - In PHP, this routine has two formats. The first format is identical to the API. The second format allows setting a matrix of all variables.
- set_var_weights
  - return = lpsolve('set_var_weights', lp, [weights])
  - No special considerations.
- set_verbose
  - lpsolve('set_verbose', lp, verbose)
  - No special considerations.
- set_XLI
  - return = lpsolve('set_XLI', lp, filename)
  - No special considerations.
- solve
  - result = lpsolve('solve', lp)
  - No special considerations.
- str_add_column
  - Not implemented.
- str_add_constraint
  - Not implemented.
- str_set_obj_fn
  - Not implemented.
- str_set_rh_vec
  - Not implemented.
- time_elapsed
  - return = lpsolve('time_elapsed', lp)
  - No special considerations.
- unscale
  - lpsolve('unscale', lp)
  - No special considerations.
- write_basis
  - lpsolve('write_basis', lp, filename)
  - No special considerations.
- write_freemps, write_freeMPS
  - return = lpsolve('write_freemps', lp, filename)
  - return = lpsolve('write_freeMPS', lp, filename)
  - In the lpsolve API, write_freeMPS needs a FILE handle. In PHP it needs the filename and thus acts the same as write_freemps.
- write_lp, write_LP
  - return = lpsolve('write_lp', lp, filename)
  - return = lpsolve('write_LP', lp, filename)
  - In the lpsolve API, write_LP needs a FILE handle. In PHP it needs the filename and thus acts the same as write_lp.
- write_mps, write_MPS
  - return = lpsolve('write_mps', lp, filename)
  - return = lpsolve('write_MPS', lp, filename)
  - In the lpsolve API, write_MPS needs a FILE handle. In PHP it needs the filename and thus acts the same as write_mps.
  - No special considerations.
- write_XLI
  - return = lpsolve('write_XLI', lp, filename {, options {, results}})
  - No special considerations.

### Extra PHP routines

These routines are not part of the lpsolve API, but are added for backwards compatibility. Most of them exist in the lpsolve API with another name.

- [names] = lpsolve('get_col_names', lp)
  - The same as get_col_name. Implemented for backwards compatibility.
- [constr_type] = lpsolve('get_constr_types', lp)
  - The same as get_constr_type. Implemented for backwards compatibility.
- [int] = lpsolve('get_int', lp)
  - The same as is_int. Implemented for backwards compatibility.
- return = lpsolve('get_no_cols', lp)
  - The same as get_Ncolumns. Implemented for backwards compatibility.
- return = lpsolve('get_no_rows', lp)
  - The same as get_Nrows. Implemented for backwards compatibility.
- name = lpsolve('get_objective_name', lp)
  - The same as get_row_name with row=0. Implemented for backwards compatibility.
- [row_vec, return] = lpsolve('get_obj_fn', lp)
  [row_vec, return] = lpsolve('get_obj_fun', lp)
  - The same as get_row with row 0. Implemented for backwards compatibility.
- name = lpsolve('get_problem_name', lp)
  - The same as get_lp_name. Implemented for backwards compatibility.
- [costs] = lpsolve('get_reduced_costs', lp)
  - The same as get_dual_solution. Implemented for backwards compatibility.
- [names] = lpsolve('get_row_names', lp)
  - The same as get_row_name. Implemented for backwards compatibility.
- [obj, x, duals, return] = lpsolve('get_solution', lp)
  - Returns the value of the objective function, the values of the variables and the duals. Implemented for backwards compatibility.
  - The return code of the call is the last value.
- value = lpsolve('mat_elm', lp)
  - The same as get_mat. Implemented for backwards compatibility.
- [handle_vec] = lpsolve('print_handle')
  - Returns a vector with open handles. Can be handy to see which handles aren't closed yet with delete_lp or free_lp.
- lp_handle = lpsolve('read_lp_file', filename {, verbose {, lp_name}})
  - The same as read_LP. Implemented for backwards compatibility.
- lp_handle = lpsolve('get_handle', lp_name)
  - Get the handle for this model from the models name. If an unknown model name is given (or already deleted), -1 is returned.
- return_constants = lpsolve('return_constants'[, return_constants])
  - Returns the setting of return_constants and optionally sets its value.

### Compile the lpsolve driver

The lpsolve PHP driver is called php_phplpsolve55.dll (windows) and phplpsolve55.so (Unix/Linux).
This driver is an interface to the lpsolve55.dll (windows) and liblpsolve55.so (Unix/Linux) lpsolve shared library that contains the implementation of lp_solve. lpsolve55.dll/liblpsolve55.so is distributed with the lp_solve package (archive lp_solve_5.5.2.14_dev.zip/lp_solve_5.5.2.14_dev.tar.gz). The lpsolve PHP driver is just a wrapper between PHP and lp_solve to translate the input/output to/from PHP and the lp_solve library.

The lpsolve PHP driver is written in C. To compile this code a C compiler is needed. Under Unix, this is the standard C compiler (c/gcc) and under windows it is the Microsoft compiler from Visual Studio .NET.

#### Windows:

First of all, the PHP sources are needed. These must be obtained from http://www.php.net
Extract the sources to a folder. In this example this is f:\php-5.2.6
Secondly, win32build.zip is needed. Note that is looks like this is only the case if method 1) is used. Method 2) works without this folder. This archive should be on that site also, but apparently it is deleted from there. It was however found on following location: http://viewcvs.php.net/viewvc.cgi/phpweb/extra/?hideattic=0
Extract the sources to \win32build. In this example this is f:\win32build

Then there are two ways to compile php_phplpsolve.dll:

1) This is somewhat the standard way, but not the easiest.
First of all, lpsolve must be under the php\ext folder. For example \php-5.2.6\ext\lpsolve
Secondly, a file config.w32 is needed. It is provided with the lpsolve PHP distribution.
To build, execute the following commands in a DOS prompt where the vcvars32.bat file of the Microsoft Visual C compiler:

    F:\php-5.2.6>buildconf.bat
    F:\php-5.2.6>cscript /nologo configure.js --without-xml --without-wddx --without-simplexml --without-dom --without-libxml --disable-zlib --without-sqlite --disable-odbc --disable-cgi --enable-cli --without-iconv --enable-phplpsolve55=shared --with-phplpsolve55path="z:\lp_solve_5.5"
    F:\php-5.2.6>nmake php_phplpsolve55.dll

Each of these commands give some messages. Also note that in the cscript command, the path to lp_solve_5.5 must be provided. In this example this is z:\lp_solve_5.5

If all is successful, php_phplpsolve.dll is made in \php-5.2.6\Release_TS

2) An easier way is using the batch files cvc6.bat or cvc8NOmsvcrt80.bat
cvc6.bat can be used for Microsoft Visual compiler version 6 and cvc8NOmsvcrt80.bat for Microsoft Visual compilers from .NET.
In this case, the lpsolve PHP files do not have to be located under \php-5.2.6\ext. Instead they can be under \lp_solve_5.5\extra\PHP\lpsolve as in the distribution.
First edit cvc6.bat or cvc8NOmsvcrt80.bat
Two commands here must be revised:

    set lp_solve=..\..
    set php=F:\php-5.2.6

Normally the first one will be ok. The second one must be changed to the path where the PHP sources are located. Here F:\php-5.2.6

To build, execute the following commands in a DOS prompt where the vcvars32.bat file of the Microsoft Visual C compiler:

    Z:\lp_solve_5.5\extra\PHP>cvc6.bat

or

    Z:\lp_solve_5.5\extra\PHP>cvc8NOmsvcrt80.bat

#### Unix/Linux:

Go to the lpsolve PHP directory and enter the following commands:

    $ phpize
    $ ./configure --enable-maintainer-zts --with-phplpsolve55=../..
    $ make

Note the ../.. path in the second command. That is the location to lp_solve_5.5 and that is normally 2 directories down.

After this is done, phplpsolve55.so is build in directory modules.

For both windows and unix/linux, don't forget to adapt php.ini as described above and possibly restart the webserver.

See also Using lpsolve from MATLAB, Using lpsolve from O-Matrix, Using lpsolve from Sysquake, Using lpsolve from Scilab, Using lpsolve from Octave, Using lpsolve from FreeMat, Using lpsolve from Euler, Using lpsolve from Python Using lpsolve from Sage, Using lpsolve from R, Using lpsolve from Microsoft Solver Foundation