Featured Posts

Finding the Current Date and Time in PHP Code

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 09-12-2009

0

Use strftime( ) or date( ) for a formatted time string

Finding the current date and time
<?php
print strftime(‘%c’);
print “\n”;
print date(‘r’);
?>
Output
Wed May 10 18:29:59 2006
Wed, 10 May 2006 18:29:59 -0400

Finding the month, day, and year
<?php
$a = getdate();
printf(‘%s %d, %d’,$a['month'],$a['mday'],$a['year']);
?>

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to Calculate Exponents in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 09-12-2009

1

To raise e to a power, use exp( ):
$exp = exp(2);// 7.3890560989307

To raise it to any power, use pow( ):
$exp = pow( 2, M_E);// 6.5808859910179

$pow = pow( 2, 10); // 1024
$pow = pow( 2, -2); // 0.25
$pow = pow( 2, 2.5);// 5.6568542494924

$pow = pow(-2, 10); // 1024
$pow = pow( 2, -2); // 0.25
$pow = pow(-2, -2.5); // NAN (Error: Not a Number)
The built-in constant M_E is an approximation of the value of e. It equals 2.7182818284590452354. So exp($n) and pow(M_E, $n) are identical.
It’s easy to create very large numbers using exp( ) and pow( ); if you outgrow PHP’s maximum size (almost 1.8e308), how to use the arbitrary precision functions. With exp( ) and pow( ), PHP returns INF (infinity) if the result is too large and NAN (not a number) on an error.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to use For Loop in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 09-12-2009

1

Use a for loop:
<?php
for ($i = $start; $i <= $end; $i++) {
plot_point($i);
}
?>
You can increment using values other than 1. For example:
<?php
for ($i = $start; $i <= $end; $i += $increment) {
plot_point($i);
}
?>
If you want to preserve the numbers for use beyond iteration,
use the range( ) method:
<?php
$range = range($start, $end);
?>
Loops like this are common. For instance, you could be plotting
a function and need to calculate the results for multiple points
on the graph. Or you could be a student counting down the number
of seconds until the end of school.
The for loop method uses a single integer and you have great
control over the loop, because you can increment and decrement
$i freely. Also, you can modify $i from inside the loop.
In the last example in the Solution, range( ) returns an array
with values from $start to $end. The advantage of using range( )
is its brevity, but this technique has a few disadvantages. For
one, a large array can take up unnecessary memory. Also, you're
forced to increment the series one number at a time, so you can't
loop through a series of even integers, for example.
It's valid for $start to be larger than $end. In this case,
the numbers returned by range( ) are in descending order. Also,
you can use it to retrieve character sequences:
<?php
print_r(range('l', 'p'));
?>
Array
(
[0] => l
[1] => m
[2] => n
[3] => o
[4] => p
)
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Syntax to Rounding Floating-Point Numbers in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 09-12-2009

1

To round a number to the closest integer, use round( ) :
$number = round(2.4); // $number = 2

To round up, use ceil( ) :
$number = ceil(2.4);// $number = 3

To round down, use floor( ) :
$number = floor(2.4); // $number = 2
If a number falls exactly between two integers, PHP rounds away from 0:
$number = round(2.5); //3

$number = round(-2.5);// -3
To keep a set number of digits after the decimal point, round( ) accepts an optional precision argument. For example, perhaps you are calculating the total price for the items in a user’s shopping cart:
<?php
$cart = 54.23;
$tax = $cart * .05;
$total = $cart + $tax; // $total = 56.9415

$final = round($total, 2); // $final = 56.94
?>

To round a number down, use the floor( ) function:
$number = floor( 2.1);//2
$number = floor( 2.9);//2
$number = floor(-2.1);// -3
$number = floor(-2.9);// -3

While to round up, use the ceil( ) function:
$number = ceil( 2.1);//3
$number = ceil( 2.9);//3
$number = ceil(-2.1);// -2
$number = ceil(-2.9);// -2

These two functions are named because when you’re rounding down, you’re rounding “toward the floor,” and when you’re rounding up, you’re rounding “toward the ceiling.”

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Variable contain valid number using PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 08-12-2009

0

How to check whether variable contains valid number using PHP

You want to ensure that a variable contains a number, even if it’s typed as a string. Alternatively, you want to check if a variable is not only a number, but is also specifically typed as a one.

Use is_numeric( ) to discover whether a variable contains a number:

<?php
if (is_numeric(5))          { /* true  */ }
if (is_numeric(’5′))        { /* true  */ }
if (is_numeric(“05″))       { /* true  */ }
if (is_numeric(‘five’))     { /* false */ }

if (is_numeric(0xDECAFBAD)) { /* true  */ }
if (is_numeric(“10e200″))   { /* true  */ }
?>

Numbers come in all shapes and sizes. You cannot assume that something is a number simply because it only contains the characters 0 through 9. What about decimal points, or negative signs? You can’t simply add them into the mix because the negative must come at the front, and you can only have one decimal point. And then there’s hexadecimal numbers and scientific notation.

Instead of rolling your own function, use is_numeric( ) to check whether a variable holds something that’s either an actual number (as in it’s typed as an integer or floating point), or it’s a string containing characters that can be translated into a number.

There’s an actual difference here. Technically, the integer 5 and the string 5 aren’t the same in PHP. However, most of the time you won’t actually be concerned about the distinction, which is why the behavior of is_numeric( ) is useful.

Helpfully, is_numeric( ) properly parses decimal numbers, such as 5.1; however, numbers with thousands separators, such as 5,100, cause is_numeric( ) to return false.

To strip the thousands separators from your number before calling is_numeric( ), use str_replace( ):

<?php
is_numeric(str_replace($number, ‘,’, ”));
?>

To check if your number is a specific type, there are a variety of related functions with self-explanatory names: is_float( ) (or is_double( ) or is_real( ); they’re all the same) and is_int( ) (or is_integer( ) or is_long( )).

To validate input data, use the techniques from Recipe 9.3 instead of is_numeric( ). That recipe describes how to check for positive or negative integers, decimal numbers, and a handful of other formats.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to Store Binary Data in Strings using PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 08-12-2009

0

You want to parse a string that contains values encoded as a binary structure or encode values into a string. For example, you want to store numbers in their binary representation instead of as sequences of ASCII characters.

1.16.2. Solution

Use pack( ) to store binary data in a string:

<?php
$packed = pack('S4',1974,106,28225,32725);
?>

Use unpack( ) to extract binary data from a string:

<?php
$nums = unpack('S4',$packed);
?>

1.16.3. Discussion

The first argument to pack( ) is a format string that describes how to encode the data that’s passed in the rest of the arguments. The format string S4 tells pack( ) to produce four unsigned short 16-bit numbers in machine byte order from its input data. Given 1974, 106, 28225, and 32725 as input on a little-endian machine, this returns eight bytes: 182, 7, 106, 0, 65, 110, 213, and 127. Each two-byte pair corresponds to one of the input numbers: 7 * 256 + 182 is 1974; 0 * 256 + 106 is 106; 110 * 256 + 65 = 28225; 127 * 256 + 213 = 32725.

The first argument to unpack( ) is also a format string, and the second argument is the data to decode. Passing a format string of S4, the eight-byte sequence that pack( ) produced returns a four-element array of the original numbers. print_r($nums) prints:

Array
(
    [1] => 1974
    [2] => 106
    [3] => 28225
    [4] => 32725
)

In unpack( ), format characters and their count can be followed by a string to be used as an array key. For example:

<?php
$nums = unpack('S4num',$packed);
print_r($nums);
?>

This prints:

Array
(
    [num1] => 1974
    [num2] => 106
    [num3] => 28225
    [num4] => 32725
)

Multiple format characters must be separated with / in unpack( ):

<?php
$nums = unpack('S1a/S1b/S1c/S1d',$packed);
print_r($nums);
?>

This prints:

Array
(
    [a] => 1974
    [b] => 106
    [c] => 28225
    [d] => 32725
)
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to Wrap the Text in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 25-11-2009

0

You need to wrap lines in a string. For example, you want to display text in <pre>/</pre> tags but have it stay within a regularly sized browser window.
Use wordwrap( ) :

<?php
$s = “Four score and seven years ago our fathers brought forth

on this continent a new nation, conceived in liberty and

dedicated to the proposition that all men are created equal.”;

print “<pre>\n”.wordwrap($s).”\n</pre>”;
?>

Output

<pre>
Four score and seven years ago our fathers brought forth on this continent
a new nation, conceived in liberty and dedicated to the proposition that
all men are created equal.
</pre>

By default, wordwrap( ) wraps text at 75 characters per line. An optional second argument specifies different line length:

<?php
print wordwrap($s,50);
?>

Output

Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in
liberty and dedicated to the proposition that all
men are created equal.

Other characters besides \n can be used for line breaks. For double spacing, use “\n\n”:

<?php
print wordwrap($s,50,”\n\n”);
?>

Output

Four score and seven years ago our fathers brought

forth on this continent a new nation, conceived in

liberty and dedicated to the proposition that all

men are created equal.

There is an optional fourth argument to wordwrap( ) that controls the treatment of words that are longer than the specified line length. If this argument is 1, these words are wrapped. Otherwise, they span past the specified line length:

<?php
print wordwrap(‘jabberwocky’,5);
print wordwrap(‘jabberwocky’,5,”\n”,1);
?>
Output
jabberwocky
jabbe
rwock
y

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to break a string into pieces in PHP

Posted by admin | Posted in PHP, Software Programs | Posted on 24-11-2009

0

You need to break a string into pieces. For example, you want to access each line that a user enters in a <textarea> form field.
Use explode( ) if what separates the pieces is a constant string:

<?php
$words = explode(‘ ‘,’My sentence is not very complicated’);
?>

Use split( ) or preg_split( ) if you need a POSIX or Perl-compatible regular expression to describe the separator:

<?php
$words = split(‘ +’,'This sentence  has  some extra whitespace  in it.’);
$words = preg_split(‘/\d\. /’,'my day: 1. get up 2. get dressed 3. eat toast’);
$lines = preg_split(‘/[\n\r]+/’,$_REQUEST['textarea']);
?>

Use spliti( ) or the /i flag to preg_split( ) for case-insensitive separator matching:

<?php
$words = spliti(‘ x ‘,’31 inches x 22 inches X 9 inches’);
$words = preg_split(‘/ x /i’,’31 inches x 22 inches X 9 inches’);
?>

The simplest solution of the bunch is explode( ). Pass it your separator string, the string to be separated, and an optional limit on how many elements should be returned:

<?php
$dwarves = ‘dopey,sleepy,happy,grumpy,sneezy,bashful,doc’;
$dwarf_array = explode(‘,’,$dwarves);
?>

This makes $dwarf_array a seven-element array, so print_r($dwarf_array) prints:
Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] => sneezy
[5] => bashful
[6] => doc
)

If the specified limit is less than the number of possible chunks, the last chunk contains the remainder:

<?php
$dwarf_array = explode(‘,’,$dwarves,5);
print_r($dwarf_array);
?>

This prints:
Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] => sneezy,bashful,doc
)

The separator is treated literally by explode( ). If you specify a comma and a space as a separator, it breaks the string only on a comma followed by a space, not on a comma or a space.
With split( ), you have more flexibility. Instead of a string literal as a separator, it uses a POSIX regular expression:

<?php
$more_dwarves = ‘cheeky,fatso, wonder boy, chunky,growly, groggy, winky’;
$more_dwarf_array = split(‘, ?’,$more_dwarves);
?>

This regular expression splits on a comma followed by an optional space, which treats all the new dwarves properly. A dwarf with a space in his name isn’t broken up, but everyone is broken apart whether they are separated by “,” or “, “. print_r($more_dwarf_array) prints:
Array
(
[0] => cheeky
[1] => fatso
[2] => wonder boy
[3] => chunky
[4] => growly
[5] => groggy
[6] => winky
)

Similar to split( ) is preg_split( ), which uses a Perl-compatible regular expression engine instead of a POSIX regular expression engine. With preg_split( ), you can take advantage of various Perl-ish regular expression extensions, as well as tricks such as including the separator text in the returned array of strings:

<?php
$math = “3 + 2 / 7 – 9″;
$stack = preg_split(‘/ *([+\-\/*]) */’,$math,-1,PREG_SPLIT_DELIM_CAPTURE);
print_r($stack);
?>

This prints:
Array
(
[0] => 3
[1] => +
[2] => 2
[3] => /
[4] => 7
[5] => -
[6] => 9
)

The separator regular expression looks for the four mathematical operators (+, -, /, *), surrounded by optional leading or trailing spaces. The PREG_SPLIT_DELIM_CAPTURE flag tells preg_split( ) to include the matches as part of the separator regular expression in parentheses in the returned array of strings. Only the mathematical operator character class is in parentheses, so the returned array doesn’t have any spaces in it.

VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

How to Create Comma Separated Data in PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 23-11-2009

0

Use the fputcsv( ) function to generate a CSV-formatted line from an array of data.  Writes the data in $sales into a file

Sample Program

<?php
$sales = array( array(‘Northeast’,’2005-01-01′,’2005-02-01′,12.54),
array(‘Northwest’,’2005-01-01′,’2005-02-01′,546.33),
array(‘Southeast’,’2005-01-01′,’2005-02-01′,93.26),
array(‘Southwest’,’2005-01-01′,’2005-02-01′,945.21),
array(‘All Regions’,'–’,'–’,1597.34) );
ob_start();
$fh = fopen(‘php://output’,'w’) or die(“Can’t open php://output”);
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) {
die(“Can’t write CSV line”);
}
}
fclose($fh) or die(“Can’t close php://output”);
$output = ob_get_contents();
ob_end_clean();
?>

<?php
$sales = array( array(‘Northeast’,’2005-01-01′,’2005-02-01′,12.54),
array(‘Northwest’,’2005-01-01′,’2005-02-01′,546.33),
array(‘Southeast’,’2005-01-01′,’2005-02-01′,93.26),
array(‘Southwest’,’2005-01-01′,’2005-02-01′,945.21),
array(‘All Regions’,'–’,'–’,1597.34) );

$fh = fopen(‘sales.csv’,'w’) or die(“Can’t open sales.csv”);
foreach ($sales as $sales_line) {
if (fputcsv($fh, $sales_line) === false) {
die(“Can’t write CSV line”);
}
}
fclose($fh) or die(“Can’t close sales.csv”);
?>

Putting comma-separated data into a string

Printing comma-separated data

<?php $sales = array( array('Northeast','2005-01-01','2005-02-01',12.54),
                array('Northwest','2005-01-01','2005-02-01',546.33),
                array('Southeast','2005-01-01','2005-02-01',93.26),
                array('Southwest','2005-01-01','2005-02-01',945.21),
                array('All Regions','--','--',1597.34) );
$fh = fopen('php://output','w');
foreach ($sales as $sales_line) {
    if (fputcsv($fh, $sales_line) === false) {
        die("Can't write CSV line");
    }
}
fclose($fh);
?>
VN:F [1.9.3_1094]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)

How to Trim Blanks from a String using PHP

Posted by admin | Posted in PHP, Software Programs, Theory Subjects | Posted on 23-11-2009

0

Use ltrim( ), rtrim( ), or trim( ), ltrim( ) removes whitespace from the beginning of a string, rtrim( ) from the end of a string, and trim( ) from both the beginning and end of a string:

<?php
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
?>
For these functions, whitespace is defined as the following
characters:newline, carriage return, space, horizontal and
vertical tab, and null .

Trimming whitespace off of strings saves storage space and canmake for more
precise display of formatted data or text within<pre> tags, for example. If
you are doing comparisons with userinput, you should trim the data first, so
that someone who mistakenly enters”98052″ as their zip code isn’t forced to
fix an error that really isn’t one. Trimming before exact text comparisons
also ensures that, for example, “salami\n” equals “salami.” It’s also a good
idea to normalize string data bytrimming it before storing it in a database.

The trim( ) functions can also remove user-specifiedcharacters from strings.
Pass the characters you want to remove as a secondargument. You can indicate
a range of characters with two dots between the firstand last characters in
the range:

<?php
// Remove numerals and space from the beginning of the line
print ltrim('10 PRINT A$',' 0..9');
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
?>

This prints:

PRINT A$
SELECT * FROM turtles

PHP also provides chop( ) asan alias for rtrim( ). However, you’re best off
using rtrim( ) instead because PHP’s chop( ) behaves differently than Perl’s
chop( ) (which is deprecated in favor of chomp( ) , anyway), and using it can
confuse others when they read your code.

VN:F [1.9.3_1094]
Rating: 6.0/10 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)