 w3programmers - Number Manipulation with PHP

# Number Manipulation with PHP

Numbers. You can’t get away from them. They’re always there, crawling around in your application, needing constant care and attention. And the more sophisticated the application is, the more demanding the numbers become. Addition and subtraction isn’t good enough anymore—now you have to perform trigonometric operations on the numbers, draw graphs with them, make them more readable with commas and padding, and yield to their logarithmic limits.

It’s almost enough to make you weep.

That’s where this Tutorial comes in. The solutions on the following pages range from the simple to the complex, but all of them address common number manipulation

tasks. In the former category are listings for converting number bases; calculating trigonometric values; checking whether numeric values are odd or even; and formatting

numbers for greater readability. In the latter category are listings to work with complex numbers and fractions; calculate standard deviation, skewness, and frequency; generate prime numbers using a technique invented by the ancient Greeks; and spell numbers as words in different languages.

## Generating a Number Range

Problem

You have two endpoints and want to generate a list of all the numbers between them.

Solution

Use PHP’s range() function:

```
<?php

// define range limits

\$x = 10;

\$y = 36;

// generate range as array

// result: (10, 11, 12...35, 36)

\$range = range(\$x, \$y);

print_r(\$range);

?>

```

The range() function accepts two arguments—a lower limit and an upper limit—and returns an array containing all the integers between, and including, those limits.

You can also create a number range that steps over particular numbers, by passing the step value to the function as a third, optional argument. The following example

illustrates this:

```
<?php

// define range limits

\$x = 10;

\$y = 30;

// generate range as array

// contains every third number

// result: (10, 13, 16, 19, 22, 25, 28)

\$range = range(\$x, \$y, 3);

print_r(\$range);

?>

```

A simple application of the range() function is to print a multiplication table. The following listing illustrates how to do this, by generating all the numbers between 1

and 10 and then using the list to print a multiplication table for the number 5:

```
<?php

// print multiplication table

foreach (range(1, 10) as \$num) {

echo "5 x \$num = " . (5 * \$num) . "\n";

}

?>

```

## Rounding a Floating Point Number

Problem

You want to round off a floating-point number.

Solution

Use the round() function:

```
<?php

// define floating point number

\$num = (2/3);

// round to integer

// result: 1

\$roundNum = round(\$num);

echo \$roundNum . "\n";

// round to 1 decimal place

// result: 0.7

\$roundNum = round(\$num, 1);

echo \$roundNum . "\n";

// round to 3 decimal places

// result: 0.667

\$roundNum = round(\$num, 3);

echo \$roundNum;

?>

```

The round() function rounds a number to a specified number of decimal places. Calling round() without the optional second argument makes it round to an integer value (0 decimal places). When rounding to an integer, the round() function will return the closest integer value. To force rounding to a lower or higher integer value, use the ceil() or floor() functions instead, as follows:

```
<?php

// define floating point numbers

\$num = (1/3);

\$r = round(\$num);

\$c = ceil(\$num);

\$f = floor(\$num);

// result: "0 1 0"

echo "\$r \$c \$f"

?>

```

## Finding the Smallest or Largest Number in an Unordered Series

Problem

You want to find the maximum or minimum value of a series of unordered numbers.

Solution

Arrange the numbers in sequence and then extract the endpoints of the sequence:

```
<?php

// define number series

\$series = array(76, 7348, 56, 2.6, 189, 67.59, 17594, 2648, 1929.79,

54, 329, 820, -1.10, -1.101);

// sort array

sort(\$series);

// extract maximum/minimum value from sorted array

// result: "Minimum is -1.101 "

\$min = \$series;

echo "Minimum is \$min ";

// result: "Maximum is 17594"

\$max = \$series[sizeof(\$series)-1];

echo "Maximum is \$max";

?>

```

There are many different ways to find the smallest or largest value in a number series. The previous listing demonstrates one of the simplest. The numbers are placed in

an array, and the sort() function is used to sort the array so that the numbers line up sequentially. The smallest value will end up at the beginning of the list—the first

element of the array—while the largest will end up at the end of the list—the last element of the array.

## Testing for Odd or Even Numbers

Problem

You want to find out if a number is odd or even.

Solution

Use PHP’s bitwise & operator:

```
<?php

// define number

\$num = 31;

// see if number is odd or even

// result: "Number is odd"

echo (1&\$num) ? "Number is odd" : "Number is even";

?>

```

For odd numbers expressed in binary format, the least significant digit is always 1, whereas for even numbers, it is always 0. PHP’s bitwise & operator returns 1 if both of

its operands are equal to 1. Using these two principles, it’s easy to create a conditional test for odd and even numbers.

If you don’t fully understand the listing above, take a look at https://www.w3programmers.com/php-basic-part-1/ for a tutorial on bitwise manipulation. Alternatively, you can consider a different test, which involves dividing the number by 2 and checking the remainder (with even numbers, the remainder will be zero). This alternative is illustrated as follows:

```
<?php

// define number

\$num = 10;

// see if number mod 2 returns a remainder

// result: "Number is even"

echo (\$num % 2) ? "Number is odd" : "Number is even";

?>

```

## Formatting Numbers with Commas

Problem

You want to make a large number more readable by using commas between groups of thousands.

Solution

Use PHP’s number_format() function:

```
<?php

// define number

\$amount = 3957459.7398;

// round and format number with commas

// result: "3,957,460"

\$formattedAmount = number_format(\$amount);

echo \$formattedAmount;

?>

```

The number_format() function is a great tool to use when formatting large integer or floating-point numbers. When invoked with a single argument, it rounds up the

number if necessary and then inserts commas between every group of thousands. Note that the output of the function is a string, not a number, and so it cannot be used

You don’t have to use the money on home improvement for the interest to be deductible. Visit this site https://cashcrazy.co.uk and learn some advice.

for further numeric manipulation. If you have a floating-point number and don’t necessarily want to round it up to an integer, you can pass number_format() a second argument, which will control the number of decimals the formatted number should contain. Here’s an example:

```
<?php

// define number

\$amount = 3957459.7398;

// format number with commas and 2 decimal places

// result: "3,957,459.74"

\$formattedAmount = number_format(\$amount, 2);

echo \$formattedAmount;

?>

```

For certain numbers, you might also want to use a custom decimal and/or thousands separator. You can accomplish this by passing number_format() two additional arguments, the first for the decimal separator and the second for the thousands separator. The next example illustrates this:

```
<?php

// define number

\$amount = 3957459.7398;

// format number with custom separator

// result: "3'957'459,74"

\$formattedAmount = number_format(\$amount, 2, ',', '\'');

echo \$formattedAmount;

?>

```

## Formatting Numbers as Currency Values

Problem

You want to format a number as per local or international currency conventions.

Solution

Define the target locale and then apply the appropriate monetary format via PHP’s money_format() function:

```
<?php

// define currency amount (in INR)

\$amount = 10000;

// display in INR

// result: "INR 10000"

setlocale(LC_MONETARY, 'en_IN');

\$inr = money_format('%i', \$amount);

echo \$inr;

// display in US dollars (convert using 1 USD = 45 INR)

// result: "\$ 222.22"

setlocale(LC_MONETARY, 'en_US');

\$usd = money_format('%n', \$amount/45);

echo \$usd;

// display in euros (convert using 1 EUR = 52 INR)

// result:

setlocale(LC_MONETARY, 'fr_FR');

\$eur = money_format('%i', \$amount/52);

echo \$eur;

?>

```

The previous listing takes a number and formats it so it conforms to Indian (INR), American (US) and European (EUR) currency conventions. The setlocale() function sets the locale, and hence the local conventions for currency display—notice that the Indian and American locales differ in their placement of thousand separators,while the European locale uses commas instead of decimals. You can make further adjustments to the display using money_format()’s wide array of format specifiers, listed at http://www.php.net/money_format. This example uses the %n and %i specifiers, which represent the national currency symbol and the three-letter international currency code without checking anything respectively.

NOTE

The money_format() function is not available in the Windows version of PHP.

## Padding Numbers with Zeroes

Problem

You want to format a number with leading or trailing zeroes.

Solution

Use the printf() or sprintf() function with appropriate format specifiers:

```
<?php

// result: 00012

printf("%05d", 12);

// result: 00169.000

printf("%09.3f", 169);

// result: 00003475.986000

printf("%015.6f", 3475.986);

// result: 74390.99

printf("%02.2f", 74390.98647);

?>

```

PHP’s printf() and sprintf() functions are very similar to the printf() and sprintf() functions that C programmers are used to, and they’re incredibly versatile when it comes to formatting both string and numeric output. Both functions accept two arguments, a series of format specifiers and the raw string or number to be formatted. The input is then formatted according to the format specifiers and the output is either displayed with printf() or assigned to a variable with sprintf(). Some common field templates are:

 Specifier What It Means %s String %d Decimal number %x Hexadecimal number %o Octal number %f Float number
`You can also combine these field templates with numbers that indicate the number of digits to display—for example, %1.2f implies that only two digits should be displayed`

after the decimal point. Adding 0 as the padding specifier tells the function to zero-pad the numbers to the specified length. You can use an alternative padding character by prefixing it with a single quote (‘). Read more at <a href=”http://www.php.net/sprintf”>http://www.php.net/sprintf</a> .

<strong> Converting Between Bases</strong>

Problem

You want to convert a number to a different base—binary, octal, hexadecimal, or custom.

<strong>Solution</strong>

Use PHP’s decbin(), decoct(), dexhec(), or base_convert() functions:

```
<?php

// define number

\$num = 100;

// convert to binary

// result: "Binary: 1100100 "

\$bin = decbin(\$num);

echo "Binary: \$bin ";

// convert to octal

// result: "Octal: 144 "

\$oct = decoct(\$num);

echo "Octal: \$oct ";

// convert to hexadecimal

// result: "Hexadecimal: 64 "

\$hex = dechex(\$num);

echo "Hexadecimal: \$hex ";

// convert to base 6;

// result: "Base6: 244"

\$base6 = base_convert(\$num, 10, 6);

echo "Base6: \$base6";

?>

```

PHP comes with a number of functions to convert a number from one base to another. The previous listing takes a base-10 (decimal) number and converts it to binary, octal, and hexadecimal with the decbin(), decoct(), and dechex() functions respectively. To convert in the opposite direction, use the bindec(), octdec(), and hexdec() functions. If you need to convert a number to or from a custom base, use the base_convert() function, which accepts three arguments: the number, the base it’s currently in, and the base it’s to be converted to. A common application of base conversion routines like this involves obtaining hexadecimal values for RGB (red, green, blue) color codes, suitable for use in Hypertext Markup Language (HTML) Web pages. The following snippet illustrates a function that does just this with the dechex() function:

```
<?php

// function to convert RGB colors to their hex values

function rgb2hex(\$r, \$g, \$b) {

return sprintf("#%02s%02s%02s", dechex(\$r), dechex(\$g),

dechex(\$b));

}

// result: "#00ff40"

\$hex = rgb2hex(0,255,64);

echo \$hex;

?>

```

## Converting Between Degrees and Radians

Problem

You want to convert an angle measurement from degrees to radians, or vice versa.

Solution

```
<?php

// result: "90 degrees = 1.57079632679 radians "

\$degrees = 90;

echo "\$degrees degrees = \$radians radians ";

// result: "1.57079632679491 radians = 90 degrees"

?>

```

The formula to convert an angle measurement in degrees (D) to radians (R) is D = R * 180/pi. Fortunately, PHP comes with a function to do it for you automatically: the deg2rad() function. Or, if you have a value that’s already in radians, you can convert it to degrees with the rad2deg() function.

## Converting Numbers into Words

Problem

You want to print a number as one or more literal words.

Solution

Use PEAR’s Numbers_Words class:

```
<?php

// include Numbers_Words class

include "Numbers/Words.php";

// create object

\$nw = new Numbers_Words();

// print numbers in words

// result: "190000000 in words is one hundred ninety million."

echo "190000000 in words is " . \$nw->toWords(190000000) . ".\n";

// result: "637 in words is six hundred thirty-seven."

echo "637 in words is " . \$nw->toWords(637) . ".\n";

// result: "-8730 in words is minus eight thousand seven hundred

thirty."

echo "-8730 in words is " . \$nw->toWords(-8730) . ".";

?>

```

The PEAR Numbers_Words class, available from http://pear.php.net/package/Numbers_Words, is designed specifically for the purpose of spelling out a number as one or more words. The class’ toWords() method accepts a positive or negative integer and outputs the corresponding string. As the previous listing illustrates, it can handle both extremely large values and negative integers. You aren’t limited to English-language strings either—the Numbers_Words class can translate your number into a variety of different languages, including German, French, Hungarian, Italian, Spanish, Russian, and Polish. The following listing illustrates this:

```
<?php

// include Numbers_Words class

include "Numbers/Words.php";

// create object

\$nw = new Numbers_Words();

// print numbers in words in different languages

// French - result: "78 in French is soixante-dix-huit."

echo "78 in French is " . \$nw->toWords(78, 'fr') . ".\n";

// Spanish - result: "499 in Spanish is cuatrocientos noventa

y nueve." echo "499 in Spanish is " . \$nw->toWords(499, 'es') . ".\n";

// German - result: "-1850000 in German is minus en million

// otte hundrede halvtreds tusinde."

echo "-1850000 in German is " . \$nw->toWords(-1850000, 'dk') . ".";

?>

```

You can obtain a complete list of supported languages from the package archive, and it’s fairly easy to create a translation table for your own language as well.

NOTE

The toWords() method does not support decimal values. To convert decimal values and fractions, consider the toCurrency() method instead.

## Converting Numbers into Roman Numerals

Problem

You want to print a number as a Roman numeral.

Solution

Use PEAR’s Numbers_Roman class:

```
<?php

// include Numbers_Roman class

include "Numbers/Roman.php";

// create object

\$nr = new Numbers_Roman();

// result: "5 in Roman is V."

echo "5 in Roman is " . \$nr->toNumeral(5) . ".\n";

// result: "318 in Roman is CCCXVIII".

echo "318 in Roman is " . \$nr->toNumeral(318) . ".";

?>

```

The PEAR Numbers_Roman class, available from http://pear.php.net/package/Numbers_Roman, translates regular numbers into their Roman equivalents. The class’ toNumeral() method accepts an integer and outputs the corresponding Roman numeral.You can print a series of Roman numerals by combining the toNumeral() method with a loop, as shown here:

```
<?php

// include Numbers_Roman class

include "Numbers/Roman.php";

// create object

\$nr = new Numbers_Roman();

// print numbers 1 to 100 as Roman numerals

// result: "I II III IV...XCVIII XCIX C"

foreach (range(1, 100) as \$x) {

print \$nr->toNumeral(\$x) . " ";

}

?>

```

You can also reverse the process with the toNumber() method, illustrated in the following code snippet:

```
<?php

// include Numbers_Roman class

include "Numbers/Roman.php";

// create object

\$nr = new Numbers_Roman();

// print CVII as an Arabic number

// result: "CVII = 107"

echo "CVII = " . \$nr->toNumber('CVII');

?>

```

NOTE

The toNumeral() method does not support decimal or negative values.

## Calculating Factorials

Problem

You want to find the factorial of a number.

Solution

Use a loop to count down and multiply the number by all the numbers between itself and 1:

```
<?php

// define number

\$num = 5;

// initialize variable

\$factorial = 1;

// calculate factorial

// by multiplying the number by all the

// numbers between itself and 1

// result: "Factorial of 5 is 120"

for (\$x=\$num; \$x>=1; \$x--) {

\$factorial = \$factorial * \$x;

}

echo "Factorial of \$num is \$factorial";

?>

```

A factorial of a number n is the product of all the numbers between n and 1. The easiest way to calculate it is with a for() loop, one that starts at n and counts down to 1. Each time the loop runs, the previously calculated product is multiplied by the current value of the loop counter. The end result is the factorial of the number n.

## Calculating Logarithms

Problem

You want to find the logarithm of a number.

Solution

Use PHP’s log() or log10() function:

```
<?php

// find natural log of 6

// result: "Natural log of 6 is 1.79175946923. "

\$logBaseE = log(6);

echo "Natural log of 6 is \$logBaseE. ";

// find base-10 log of 5

// result: "Base10 log of 5 is 0.698970004336."

\$logBase10 = log10(5);

echo "Base10 log of 5 is \$logBase10.";

?>

```

Logarithms come in handy when you are solving differential equations, and most scientific calculators enable you to easily calculate the natural and base-10 logarithm of any number. PHP is no different—its log() and log10() functions return the natural and base-10 logarithm of their input argument. To calculate the logarithm for any other base, you would normally use the logarithmic property log YX = log bX / log bY. In PHP, you can instead simply specify the base as a second parameter to log(), as shown here:

```
<?php

// find binary (base-2) log of 10

// result: "Binary log of 10 is 3.32192809489"

\$logBase2 = log(10, 2);

echo "Binary log of 10 is \$logBase2";

?>

```

The exponential function does the reverse of the natural logarithmic function, and is expressed in PHP through the exp() function. The following listing illustrates its usage:

```
<?php

// find e ^ \$num

// result: "Exponent of 0.69315 is 2"

\$exponentE = exp(0.69315);

echo "Exponent of 0.69315 is " . round(\$exponentE, 2);

?>

```

## Calculating Trigonometric Values

Problem

You want to perform a trigonometric calculation, such as finding the sine or cosine of an angle.

Solution

Use one of PHP’s numerous trigonometric functions:

```
<?php

// define angle

\$angle = 45;

// calculate sine

// result: "Sine: 0.850903524534 "

\$sine = sin(\$angle);

echo "Sine: \$sine \n";

// calculate cosine

// result: "Cosine: 0.525321988818 "

\$csine = cos(\$angle);

echo "Cosine: \$csine \n";

// calculate tangent

// result: "Tangent: 1.61977519054 "

\$tangent = tan(\$angle);

echo "Tangent: \$tangent \n";

// calculate arc sine

// result: "Arc sine: -1.#IND "

\$arcSine = asin(\$angle);

echo "Arc sine: \$arcSine \n";

// calculate arc cosine

// result: "Arc cosine: -1.#IND "

\$arcCsine = acos(\$angle);

echo "Arc cosine: \$arcCsine \n";

// calculate arc tangent

// result: "Arc tangent: 1.54857776147 "

\$arcTangent = atan(\$angle);

echo "Arc tangent: \$arcTangent \n";

// calculate hyperbolic sine

// result: "Hyperbolic sine: 1.74671355287E+019 "

\$hypSine = sinh(\$angle);

echo "Hyperbolic sine: \$hypSine \n";

// calculate hyperbolic cosine

// result: "Hyperbolic cosine: 1.74671355287E+019 "

\$hypCsine = cosh(\$angle);

echo "Hyperbolic cosine: \$hypCsine \n";

// calculate hyperbolic tangent

// result: "Hyperbolic tangent: 1 "

\$hypTangent = tanh(\$angle);

echo "Hyperbolic tangent: \$hypTangent \n";

?>

```

PHP comes with a rich toolkit of functions designed specifically to assist in trigonometry. With these functions, you can calculate sines, cosines, and tangents for any angle. While there aren’t yet built-in functions to calculate secants, cosecants,and cotangents, it’s still fairly easy to calculate these inversions with the functions that are available. PHP also includes functions to calculate hyperbolic and inverse hyperbolic sines, cosines, and tangents; read more about these at http://www.php.net/math.

## Calculating Future Value

Problem

You want to find the future value of a sum of money, given a fixed interest rate.

Solution

Calculate the future value by compounding the sum over various periods using the supplied interest rate:

```
<?php

// define present value

\$presentValue = 100000;

// define interest rate per compounding period

\$intRate = 8;

// define number of compounding periods

\$numPeriods = 6;

// calculate future value assuming compound interest

// result: "100000 @ 8 % over 6 periods becomes 158687.43"

\$futureValue = round(\$presentValue * pow(1 + (\$intRate/100),

\$numPeriods), 2);

echo "\$presentValue @ \$intRate % over \$numPeriods periods becomes

\$futureValue";

?>

```

The formula to calculate the future value (F) of a particular amount (P), given a fixed interest rate (r) and a fixed number of years (n) is F = P(1 + r/100)n. Performing the calculation in PHP is a simple matter of turning this formula into executable code. Nevertheless, you’d be surprised how many novice programmers forget all about PHP’s operator precedence rules and, as a result, generate incorrect results. The previous listing uses braces to correctly define the order in which the variables are processed.

## Calculating Statistical Values

Problem

You want to calculate statistical measures, such as variance or skewness, for a number set.

Solution

Use PEAR’s Math_Stats class:

```
<?php

// include Math_Stats class

include "Math/Stats.php";

// initialize object

\$stats = new Math_Stats();

// define number series

\$series = array(76, 7348, 56, 2.6, 189, 67.59, 17594, 2648, 1929.79,

54, 329, 820);

// connect object to series

\$stats->setData(\$series);

// calculate complete statistics

\$data = \$stats->calcFull();

print_r(\$data);

?>

```

PEAR’s Math_Stats class, available from http://pear.php.net/package/Math_Stats, is designed specifically to calculate statistical measures for a set of numbers. This number set must be expressed as an array, and passed to the class’ setData() method. The calcFull() method can then be used to generate a basic or expanded set of statistics about the number set. The return value of this method is an associative array, with keys for each statistical measure calculated. For example, the variable \$data[‘median’] would return the median of the number set.

## Generating Unique Identifiers

Problem

You want to generate a unique, random numeric identifier that cannot be easily guessed.

Solution

Use a combination of PHP’s uniqid(), md5(), and rand() functions:

```
<?php

// generate a random, unique ID

// result: "5542ec0a1928b99ef90cb87503094fe4" (example)

\$id = md5(uniqid(rand(), true));

echo \$id;

?>

```

PHP’s uniqid() function returns an alphanumeric string based on the current time in microseconds, suitable for use in any operation or transaction that is keyed on a unique alphanumeric string. Because the identifier is based on a time value, there is a very slight possibility of two identical identifiers being generated at the same instant; to reduce this possibility, add a random element to the procedure by combining the call to uniqid() with a call to rand() and md5().

## Generating Random Numbers

Problem

You want to generate one or more random numbers.

Solution

Use PHP’s rand() function:

```
<?php

// generate a random number

// result: 18785 (example)

echo rand();

// generate a random number between 0 and 100

// result: 4 (example)

echo rand(0, 100);

?>

```

Generating a random number in PHP is as simple as calling the rand() function. If you’d optionally like to limit the random number to a specific range, you can pass rand() the upper and lower limits of the range. To obtain a random floating-point number, divide the random number produced by a very large value. The getrandmax() function is a good choice here—it returns the maximum value that rand() could possibly generate on your system. Here’s an illustration:

```
<?php

// generate a random floating-point number

// result: 0.721182897427 (example)

echo rand()/getrandmax();

?>

```

If you need more than one random number, use rand() in combination with aloop and array. Here’s an example:

```
<?php

// generate a series of 10 random numbers between 0 and 100

// result: "12 95 88 87 61 49 61 4 99 75" (example)

for (\$x=0; \$x<10; \$x++) {

echo rand(0, 100) . " ";

}

?> ```

## Generating Prime Numbers

Problem

You want to generate a series of prime numbers, or find out if a particular number is prime.

Solution

Use the Sieve of Eratosthenes to filter out all the numbers that are not prime and display the rest:

```
<?php

// list all primes between 2 and some integer

// using the Sieve of Erastothenes

function listPrimes(\$end) {

// generate an array of all possible integers

// between the first prime and the supplied limit

\$sieve = range(2, \$end);

// retrieve the size of the array

\$size = sizeof(\$sieve);

// reset internal array pointer to beginning of array

reset(\$sieve);

// iterate over the array

while (list(\$key, \$val) = each(\$sieve)) {

// for each element

// check if subsequent elements are divisible by it

// remove them from the array if so

for (\$x=\$key+1; \$x<\$size; \$x++) {

if (\$sieve[\$x] % \$val == 0) {

unset(\$sieve[\$x]);

}

}

}

// at the end, elements left in array are primes

return \$sieve;

}

// list all the primes between 2 and 100

// result: "2 3 5 7...83 89 97"

echo implode(" ", listPrimes(100));

?>

```

A prime number is a number that has only two divisors: itself and 1. There are quite a few ways to generate a sequence of prime numbers, but the method listed previously is one of the oldest (and also one of the most efficient). Known as the Sieve of Eratosthenes, after the Greek scholar of the same name, it essentially requires you to perform three steps:

• List all the integers between 2 and some number n.
• Begin with the fi rst number in the list. Remove all the numbers from the list that are (a) greater than it, and (b) multiples of it.
• Move to the next available number and repeat the process.

The numbers left behind after this filtering, or sieving, process will be prime numbers—that is, numbers that cannot be divided by any other number except themselves and 1.

## Generating Fibonacci Numbers

Problem

You want to generate a series of Fibonacci numbers, or find out if a particular number belongs to the Fibonacci sequence.

Solution

Define the first two numbers, and use a loop to calculate the rest:

```
<?php

// generate the first N Fibonacci numbers

function generateFibonacciNumbers(\$size) {

// define array to hold Fibonacci numbers

\$fibonacciArray = array();

\$fibonacciArray = 0; // by definition

\$fibonacciArray = 1; // by definition

// generate numbers

for (\$x=2; \$x<=\$size; \$x++) {

\$fibonacciArray[\$x] = \$fibonacciArray[\$x-2] +

\$fibonacciArray[\$x-1];

}

// return array

return \$fibonacciArray;

}

// list the first 20 Fibonacci numbers

// result: "0 1 1 2 3 5 8...2584 4181 6765"

echo implode(" ", generateFibonacciNumbers(20));

?>

```

1. Zubair
2. prakash mishra