Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

What Is File Upload?

Answer»

File UPLOAD is Web page FUNCTION which allows visitor to specify a file on the browser's system and submit it to the Web server. This is a very USEFUL function for many interactive Web sites. Some examples are:

  • Web base email systems for users to send attachments.
  •  Forums that allows user to submit pictures.
  •  Web sites file managers for users to build their own Web pages.

Which HTML Tag Allows Users to Specify a File for Uploading?
To present an input field on your Web page to allow users to specify a local file to upload, you need to use the <INPUT TYPE="FILE" ...> tag inside a <FORM ...> tag. The <INPUT TYPE="FILE" ...> will be displayed as a text input field followed by a BUTTON called "Browse...". Users can either enter the full path name of a local file, or click Browse button to go through a dialog box to select a file interactively. The following PHP CODE shows you a good example of the file upload tag:

<?php print("<html><form>n"); print("<input type=file>n"); print("<input type=submit>n"); print("</form></html>n"); ?>

File upload is Web page function which allows visitor to specify a file on the browser's system and submit it to the Web server. This is a very useful function for many interactive Web sites. Some examples are:

Which HTML Tag Allows Users to Specify a File for Uploading?
To present an input field on your Web page to allow users to specify a local file to upload, you need to use the <INPUT TYPE="FILE" ...> tag inside a <FORM ...> tag. The <INPUT TYPE="FILE" ...> will be displayed as a text input field followed by a button called "Browse...". Users can either enter the full path name of a local file, or click Browse button to go through a dialog box to select a file interactively. The following PHP code shows you a good example of the file upload tag:

2.

What Is A Result Set Object?

Answer»

A result set object is a logical representation of data rows returned by mysql_query() function on SELECT statements. Every result set object has an INTERNAL pointer USED to identify the current row in the result set. Once you GET a result set object, you can USE the following functions to retrieve detail information:
• mysql_free_result($rs) - Closes this result set object.
• mysql_num_rows($rs) - Returns the number rows in the result set.
• mysql_num_fields($rs) - Returns the number fields in the result set.
• mysql_fetch_row($rs) - Returns an array contains the current row INDEXED by field position numbers.
• mysql_fetch_assoc($rs) - Returns an array contains the current row indexed by field names.
• mysql_fetch_array($rs) - Returns an array contains the current row with double indexes: field position numbers and filed names.
• mysql_fetch_lengths($rs) - Returns an array contains lengths of all fields in the last row returned.
• mysql_field_name($rs, $i) - Returns the name of the field of the specified index.

A result set object is a logical representation of data rows returned by mysql_query() function on SELECT statements. Every result set object has an internal pointer used to identify the current row in the result set. Once you get a result set object, you can use the following functions to retrieve detail information:
• mysql_free_result($rs) - Closes this result set object.
• mysql_num_rows($rs) - Returns the number rows in the result set.
• mysql_num_fields($rs) - Returns the number fields in the result set.
• mysql_fetch_row($rs) - Returns an array contains the current row indexed by field position numbers.
• mysql_fetch_assoc($rs) - Returns an array contains the current row indexed by field names.
• mysql_fetch_array($rs) - Returns an array contains the current row with double indexes: field position numbers and filed names.
• mysql_fetch_lengths($rs) - Returns an array contains lengths of all fields in the last row returned.
• mysql_field_name($rs, $i) - Returns the name of the field of the specified index.

3.

How To Get The Number Of Rows Selected Or Affected By A Sql Statement?

Answer»

There are two functions you can USE the get the number of ROWS selected or affected by a SQL statement:

  • mysql_num_rows($rs) - Returns the number of rows selected in a result SET OBJECT returned from SELECT statement.
  • mysql_affected_rows() - Returns the number of rows affected by the last INSERT, UPDATE or DELETE statement.

There are two functions you can use the get the number of rows selected or affected by a SQL statement:

4.

How To Run A Sql Statement?

Answer»

You can run any types of SQL STATEMENTS through the mysql_query() FUNCTION. It takes the SQL statement as a STRING and returns different types of data depending on the SQL statement type and execution status:
• Returning FALSE, if the execution failed.
• Returning a result set object, if the execution is successful on a SELECT statement or other statement returning multiple rows of data.
• Returning TRUE, if the execution is successful on other statements.
Here is a good EXAMPLE of running a SQL statement with the mysql_query() function:
<?php
include "mysql_connection.php";
$sql = 'SELECT sysdate() FROM dual';
$rs = mysql_query($sql, $con);
$row = mysql_fetch_array($rs);
print("Database current time: ". $row[0] ."\n");
mysql_close($con);
?>

You can run any types of SQL statements through the mysql_query() function. It takes the SQL statement as a string and returns different types of data depending on the SQL statement type and execution status:
• Returning FALSE, if the execution failed.
• Returning a result set object, if the execution is successful on a SELECT statement or other statement returning multiple rows of data.
• Returning TRUE, if the execution is successful on other statements.
Here is a good example of running a SQL statement with the mysql_query() function:
<?php
include "mysql_connection.php";
$sql = 'SELECT sysdate() FROM dual';
$rs = mysql_query($sql, $con);
$row = mysql_fetch_array($rs);
print("Database current time: ". $row[0] ."\n");
mysql_close($con);
?>

5.

How To Connect To Mysql From A Php Script?

Answer»

If you want ACCESS the MySQL SERVER, you must create a connection object first by calling the mysql_connect() function in the following format:
$con = mysql_connect($server, $username, $password);
If you are CONNECTING to a local MySQL server, you don't need to specify username and password. If you are connecting to a MySQL server offered by your Web hosting company, they will provide you the server name, username, and password.
The following script SHOWS you how to connect to a local MySQL server, obtained server information, and closed the connection:
<?php
$con = mysql_connect('localhost');
print(mysql_get_server_info($con)."\n");
print(mysql_get_host_info($con)."\n");
mysql_close($con);
?>

If you want access the MySQL server, you must create a connection object first by calling the mysql_connect() function in the following format:
$con = mysql_connect($server, $username, $password);
If you are connecting to a local MySQL server, you don't need to specify username and password. If you are connecting to a MySQL server offered by your Web hosting company, they will provide you the server name, username, and password.
The following script shows you how to connect to a local MySQL server, obtained server information, and closed the connection:
<?php
$con = mysql_connect('localhost');
print(mysql_get_server_info($con)."\n");
print(mysql_get_host_info($con)."\n");
mysql_close($con);
?>

6.

What Do You Need To Connect Php To Mysql?

Answer»

If you WANT to access MySQL database server in your PHP script, you need to make sure that MySQL module is installed and turned on in your PHP engine. CHECK the PHP configuration file, php.ini, to make sure the extension=php_mysql.dll is not commented out.
The MySQL module offers a number of functions to allow you to work with MySQL server. Some commonly used MySQL functions are:
• mysql_connect -- Open a CONNECTION to a MySQL Server
• mysql_close -- Close MySQL connection
• mysql_db_query -- Send a MySQL query
• mysql_fetch_array -- Fetch a RESULT row as an associative array, a numeric array, or both
• mysql_free_result -- FREE result memory
• mysql_list_tables -- List tables in a MySQL database
• mysql_list_fields -- List MySQL table fields

If you want to access MySQL database server in your PHP script, you need to make sure that MySQL module is installed and turned on in your PHP engine. Check the PHP configuration file, php.ini, to make sure the extension=php_mysql.dll is not commented out.
The MySQL module offers a number of functions to allow you to work with MySQL server. Some commonly used MySQL functions are:
• mysql_connect -- Open a connection to a MySQL Server
• mysql_close -- Close MySQL connection
• mysql_db_query -- Send a MySQL query
• mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both
• mysql_free_result -- Free result memory
• mysql_list_tables -- List tables in a MySQL database
• mysql_list_fields -- List MySQL table fields

7.

What Is Session_register()?

Answer»

session_register() is OLD function that REGISTERS global variables into the current session. You should stop using session_register() and USE array $_SESSION to save values into the current session now.

session_register() is old function that registers global variables into the current session. You should stop using session_register() and use array $_SESSION to save values into the current session now.

8.

How To Close A Session Properly?

Answer»

Let's say you site requires users to login. When a logged in user CLICKS the logout BUTTON, you need to close the session associated with this user properly in 3 steps:
1. Remove all session values with $_SESSION = array().
2. Remove the session ID cookie with the setcookie() function.
3. Destroy the session object with the session_destroy() function.
Below is a good sample script:
<?PHP
session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
print("<html&GT;<pre>");
print("Thank you for visiting PICKZYCenter.com.\n");
print(" <a href=login.php>Login Again.</a>\n");
print("</pre></html>\n");
?>

Let's say you site requires users to login. When a logged in user clicks the logout button, you need to close the session associated with this user properly in 3 steps:
1. Remove all session values with $_SESSION = array().
2. Remove the session ID cookie with the setcookie() function.
3. Destroy the session object with the session_destroy() function.
Below is a good sample script:
<?php
session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
print("<html><pre>");
print("Thank you for visiting PICKZYCenter.com.\n");
print(" <a href=login.php>Login Again.</a>\n");
print("</pre></html>\n");
?>

9.

How To Remove Values Saved In The Current Session?

Answer»

If you want to remove values saved in the CURRENT session, you should USE the UNSET() function on those saved values in $_SESSION, or use array() to EMPTY $_SESSION:

  • unset($_SESSION['MyColor']) - Removes one value named MyColor in the current session.
  • $_SESSION = array() - Removes all values in the current session.
  • unset($_SESSION) - Bad statement. It may AFFECT the session mechanism.

If you want to remove values saved in the current session, you should use the unset() function on those saved values in $_SESSION, or use array() to empty $_SESSION:

10.

How To Set Session.gc_divisor Properly?

Answer»

As you know that session.gc_divisor is the FREQUENCY of when the session GARBAGE collection process will be executed. You should SET this value based on the income request traffic. Here are some suggestions:
# Set it to 10, if traffic is less than 10,000 PER day:
session.gc_divisor = 10
# Set it to 100, if traffic is between 10,000 and 100,000 per day:
session.gc_divisor = 100
# Set it to 1000, if traffic is greater than 100,000 per day:
session.gc_divisor = 1000

As you know that session.gc_divisor is the frequency of when the session garbage collection process will be executed. You should set this value based on the income request traffic. Here are some suggestions:
# Set it to 10, if traffic is less than 10,000 per day:
session.gc_divisor = 10
# Set it to 100, if traffic is between 10,000 and 100,000 per day:
session.gc_divisor = 100
# Set it to 1000, if traffic is greater than 100,000 per day:
session.gc_divisor = 1000

11.

How To Set Session.gc_maxlifetime Properly?

Answer»

As you know that session.gc_maxlifetime is the session value timeout period. You should SET this value based on the USAGE pattern of your visitors. Here are some suggestions:
# Set it to 20 minutes for a normal Web site:
session.gc_maxlifetime = 1200
# Set it to 24 hours if visitors comes to the site many time a DAY:
# EXAMPLE: Yahoo EMAIL site expires your session in 24 hours.
session.gc_maxlifetime = 86400

As you know that session.gc_maxlifetime is the session value timeout period. You should set this value based on the usage pattern of your visitors. Here are some suggestions:
# Set it to 20 minutes for a normal Web site:
session.gc_maxlifetime = 1200
# Set it to 24 hours if visitors comes to the site many time a day:
# Example: Yahoo email site expires your session in 24 hours.
session.gc_maxlifetime = 86400

12.

What Is The Timeout Period On Session Values?

Answer»

The PHP engine has no DIRECT settings on session timeout period. But it has a session garbage collection mechanism that you can set to remove those special files containing session values. There are 3 settings you can use to define the session garbage collection mechanism:
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
The first TWO settings tell the PHP engine to run the garbage collection process once every 1000 requests received by the Web server. The last setting tells the PHP engine to treat session values as garbage 1440 seconds after they have not been used.
Putting all settings together, your session values probably be removed 1440 seconds after the visitor stopping using your Web site. The probability of this removal is one over 1000 requests received after the 1440-second period.
In another word, if visitor John stopped using your site, and there is no other visitors COMING to your site, session values created for John will never be removed. However, if you have a busy site, like 1000 requests per MINUTE, John's session values will be removed about one minute plus 1440 seconds after John stopped using the site.

The PHP engine has no direct settings on session timeout period. But it has a session garbage collection mechanism that you can set to remove those special files containing session values. There are 3 settings you can use to define the session garbage collection mechanism:
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
The first two settings tell the PHP engine to run the garbage collection process once every 1000 requests received by the Web server. The last setting tells the PHP engine to treat session values as garbage 1440 seconds after they have not been used.
Putting all settings together, your session values probably be removed 1440 seconds after the visitor stopping using your Web site. The probability of this removal is one over 1000 requests received after the 1440-second period.
In another word, if visitor John stopped using your site, and there is no other visitors coming to your site, session values created for John will never be removed. However, if you have a busy site, like 1000 requests per minute, John's session values will be removed about one minute plus 1440 seconds after John stopped using the site.

13.

Is It More Secure To Use Cookies To Transfer Session Ids?

Answer»

yes, because attacking your WEB site using URL PARAMETERS is much easier than using cookies.
So if you are the SYSTEM administrator of your Web server, you should set session.use_only_cookies=1.
If your Web server is PROVIDED by a hosting service PROVIDER, ask them to set session.use_only_cookies=1.

yes, because attacking your Web site using URL parameters is much easier than using cookies.
So if you are the system administrator of your Web server, you should set session.use_only_cookies=1.
If your Web server is provided by a hosting service provider, ask them to set session.use_only_cookies=1.

14.

What Are The Options To Transfer Session Ids?

Answer»

Once a new session is created, its session ID MUST be transferred to the CLIENT browser and included in the next client request, so that the PHP engine can find the same session created by the same visitor. The PHP engine has two options to transfer the session ID to the client browser:

  • As URL parameter - The Session ID will be embedded in all URLs in the HTML DOCUMENT delivered to the client browser. When the visitor clicks any of those URLs, the session ID will be returned back to the Web server as part of the requesting URL.
  • As a cookie - The session ID will be delivered as a cookie to the client browser. When visitor requests any other pages on the Web server, the session ID will be returned back to the Web server ALSO as a cookie.

The PHP engine is configured to use URL parameters for transferring session IDs by DEFAULT.

Once a new session is created, its session ID must be transferred to the client browser and included in the next client request, so that the PHP engine can find the same session created by the same visitor. The PHP engine has two options to transfer the session ID to the client browser:

The PHP engine is configured to use URL parameters for transferring session IDs by default.

15.

How Does Firefox Manage Cookies?

Answer»

FireFox browser allows you to delete old cookies, and gives you options to keep persistent cookies in cookie files until they REACH their EXPIRATION time. The following tutorial shows you how to manage cookies in FireFox:
• Run FireFox
• Go to Tools/Options
• Click Privacy and then Cookies
• Click the Clear button to delete all old cookies
• Change the Keep Cookies option to "until they EXPIRE" to ALLOW persistent cookies to be store a cookie FILE.

FireFox browser allows you to delete old cookies, and gives you options to keep persistent cookies in cookie files until they reach their expiration time. The following tutorial shows you how to manage cookies in FireFox:
• Run FireFox
• Go to Tools/Options
• Click Privacy and then Cookies
• Click the Clear button to delete all old cookies
• Change the Keep Cookies option to "until they expire" to allow persistent cookies to be store a cookie file.

16.

How To Delete Cookie Files On Your Computer?

Answer»

A simple way to delete cookie files on your COMPUTER is to use the FUNCTION offered by the IE browser. The following tutorial EXERCISE shows you how to delete cookie files created by IE:
OPEN IE (Internet Explorer)
• Go to OPTIONS/Internet Options
• Click the Delete Cookies button on the options dialog window.
Check the cookie directory again. All cookie files should be deleted.

A simple way to delete cookie files on your computer is to use the function offered by the IE browser. The following tutorial exercise shows you how to delete cookie files created by IE:
• Open IE (Internet Explorer)
• Go to Options/Internet Options
• Click the Delete Cookies button on the options dialog window.
Check the cookie directory again. All cookie files should be deleted.

17.

Where Are The Persistent Cookies Stored On Your Computer?

Answer»

The location and file names where persistent cookies are stored on your computer depend on which browser you are using. If you using Microsoft Internet Explorer, persistent cookies are stored in the \Documents and Settings\$user\Cookies DIRECTORY. Cookies are stored in multiple cookie files with one file per WEB SERVER. Check your cookie directory on your local SYSTEM, you will be surprised to see how many Web SERVERS are setting persistent cookies to your computer.

The location and file names where persistent cookies are stored on your computer depend on which browser you are using. If you using Microsoft Internet Explorer, persistent cookies are stored in the \Documents and Settings\$user\Cookies directory. Cookies are stored in multiple cookie files with one file per Web server. Check your cookie directory on your local system, you will be surprised to see how many Web servers are setting persistent cookies to your computer.

18.

How Cookies Are Transported From Browsers To Servers?

Answer»

Cookies are transported from a WEB browser to a Web SERVER in the header area of the HTTP request message. Each COOKIE will be included in a separate "Cookie:" header line in the following format:
GET / HTTP/1.1
Cookie: name1=value1
Cookie: name2=value2
Cookie: name3=value3
......
Accept: */*

Cookies are transported from a Web browser to a Web server in the header area of the HTTP request message. Each cookie will be included in a separate "Cookie:" header line in the following format:
GET / HTTP/1.1
Cookie: name1=value1
Cookie: name2=value2
Cookie: name3=value3
......
Accept: */*

19.

How Cookies Are Transported From Servers To Browsers?

Answer»

Cookies are transported from a WEB server to a Web browser in the header area of the HTTP response MESSAGE. Each COOKIE will be included in a SEPARATE "Set-Cookie:" header line in the following format:
Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal.

Cookies are transported from a Web server to a Web browser in the header area of the HTTP response message. Each cookie will be included in a separate "Set-Cookie:" header line in the following format:
Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal.

20.

How To Receive A Cookie From The Browser?

Answer»

If you know that a cookie has been sent to the BROWSER when it was visiting the server PREVIOUSLY, you can check the built-in $_COOKIE array, which contains all COOKIES that were sent by the server previously. The script below shows you how to pickup one cookie from the $_COOKIE and loop through all cookies in $_COOKIE:
&LT;?php
if (isset($_COOKIE["LoginName"])) {
$loginName = $_COOKIE["LoginName"];
print("RECEIVED a cookie named as LoginName: ".$loginName."\n");
} else {
print("Did not received any cookie named as LoginName.\n");
}
print("All cookies received:\n");
foreach ($_COOKIE as $name => $value) {
print " $name = $value\n";
}
?>

If you know that a cookie has been sent to the browser when it was visiting the server previously, you can check the built-in $_COOKIE array, which contains all cookies that were sent by the server previously. The script below shows you how to pickup one cookie from the $_COOKIE and loop through all cookies in $_COOKIE:
<?php
if (isset($_COOKIE["LoginName"])) {
$loginName = $_COOKIE["LoginName"];
print("Received a cookie named as LoginName: ".$loginName."\n");
} else {
print("Did not received any cookie named as LoginName.\n");
}
print("All cookies received:\n");
foreach ($_COOKIE as $name => $value) {
print " $name = $value\n";
}
?>

21.

How To Send A Cookie To The Browser?

Answer»

If you want to sent a cookie to the browser when it comes to request your PHP page, you can use the setcookie( ) function. Note that you should call setcookie() function before any output statements. The following script shows you how to SET COOKIES:
<?php
setcookie("LoginName","XYZ");
setcookie("PreferredColor","Blue");
print("2 cookies were delivered.\n");
?&GT;

If you want to sent a cookie to the browser when it comes to request your PHP page, you can use the setcookie( ) function. Note that you should call setcookie() function before any output statements. The following script shows you how to set cookies:
<?php
setcookie("LoginName","XYZ");
setcookie("PreferredColor","Blue");
print("2 cookies were delivered.\n");
?>

22.

How To Support Multiple-page Forms?

Answer»

If you have a long form with a lots of fields, you may want to DIVIDE the fields into MULTIPLE groups and present multiple pages with one group of fields on one page. This makes the a long form more user-friendly. However, this requires you to write good scripts that:
• When processing the first page and other middle pages, you must keep those input VALUES collected so far in the session or as hidden values in the next page form.
• When processing the last page, you should collect all input values from all pages for final process, LIKE saving EVERYTHING to the database.

If you have a long form with a lots of fields, you may want to divide the fields into multiple groups and present multiple pages with one group of fields on one page. This makes the a long form more user-friendly. However, this requires you to write good scripts that:
• When processing the first page and other middle pages, you must keep those input values collected so far in the session or as hidden values in the next page form.
• When processing the last page, you should collect all input values from all pages for final process, like saving everything to the database.

23.

How To Retrieve The Original Query String?

Answer»

If you have CODED some values in the URL without USING the standard form GET format, you need to retrieve those values in the ORIGINAL query string in $_SERVER['QUERY_STRING']. The script below is an ENHANCED version of processing_forms.php which print the original query string:
<?php
print("<html><pre>");
print(" query_string = {$_SERVER['QUERY_STRING']}\n");
$count = count($_REQUEST);
print("Number of values: $count\n");
foreach ($_REQUEST as $KEY=>$value) {
if (is_array($value)) {
print(" $key is an array\n");
for ($i = 0; $i < count($value); $i++) {
$sub_value = $value[$i];
if (get_magic_quotes_gpc()) {
$sub_value = stripslashes($sub_value);
}
print(" ".$key."[".$i."] = ".$sub_value."\n");
}
} else {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
print(" $key = $value\n");
}
}
print("</pre></html>\n");
?>

If you have coded some values in the URL without using the standard form GET format, you need to retrieve those values in the original query string in $_SERVER['QUERY_STRING']. The script below is an enhanced version of processing_forms.php which print the original query string:
<?php
print("<html><pre>");
print(" query_string = {$_SERVER['QUERY_STRING']}\n");
$count = count($_REQUEST);
print("Number of values: $count\n");
foreach ($_REQUEST as $key=>$value) {
if (is_array($value)) {
print(" $key is an array\n");
for ($i = 0; $i < count($value); $i++) {
$sub_value = $value[$i];
if (get_magic_quotes_gpc()) {
$sub_value = stripslashes($sub_value);
}
print(" ".$key."[".$i."] = ".$sub_value."\n");
}
} else {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
print(" $key = $value\n");
}
}
print("</pre></html>\n");
?>

24.

How To List All Values Of Submitted Fields?

Answer»

If you want list all values of submitted FIELDS, you can write a simple LOOP to retrieve all ENTRIES in the $_REQUEST array. Below is an improved version of processing_forms.php to list all submited input values:
<?php
PRINT("<html><pre>");
$count = count($_REQUEST);
print("NUMBER of values: $count\n");
foreach ($_REQUEST as $key=>$value) {
print(" $key = $value\n");
}
print("</pre></html>\n");
?>

If you want list all values of submitted fields, you can write a simple loop to retrieve all entries in the $_REQUEST array. Below is an improved version of processing_forms.php to list all submited input values:
<?php
print("<html><pre>");
$count = count($_REQUEST);
print("Number of values: $count\n");
foreach ($_REQUEST as $key=>$value) {
print(" $key = $value\n");
}
print("</pre></html>\n");
?>

25.

How To Avoid The Undefined Index Error?

Answer»

If you don't want your PHP page to give out errors as shown in the PREVIOUS exercise, you should consider checking all expected input FIELDS in $_REQUEST with the isset() FUNCTION as shown in the example script below:
<?php
if (isset($_REQUEST['name'])) {
$name = $_REQUEST['name'];
} else {
$name = "";
}
if (isset($_REQUEST['comment'])) {
$comment = $_REQUEST['comment'];
} else {
$comment = "";
}
print("<html><pre>");
print("You have submitted the following information:\n");
print(" Name = $name\n");
print(" COMMENTS = $comment\n");
print("Thank you!\n");
print("</pre></html>\n");
?>

If you don't want your PHP page to give out errors as shown in the previous exercise, you should consider checking all expected input fields in $_REQUEST with the isset() function as shown in the example script below:
<?php
if (isset($_REQUEST['name'])) {
$name = $_REQUEST['name'];
} else {
$name = "";
}
if (isset($_REQUEST['comment'])) {
$comment = $_REQUEST['comment'];
} else {
$comment = "";
}
print("<html><pre>");
print("You have submitted the following information:\n");
print(" Name = $name\n");
print(" Comments = $comment\n");
print("Thank you!\n");
print("</pre></html>\n");
?>

26.

What Happens If An Expected Input Field Was Not Submitted?

Answer»

Obviously, if an expected input field was not submitted, there will no entry in the $_REQUEST array for that field. You may get an execution error, if you are not checking the EXISTENCE of the expected entries in $_REQUEST. For example, if you copy processing_forms.php to your local Web server, and run your browser with http://localhost/processing_forms.php?name=Joe, you will an error page like this:
You have submitted the following INFORMATION:
Name = Joe
COMMENTS =
Thank you!
PHP Notice: UNDEFINED index:
comment in ...\processing_forms.php on line 3

Obviously, if an expected input field was not submitted, there will no entry in the $_REQUEST array for that field. You may get an execution error, if you are not checking the existence of the expected entries in $_REQUEST. For example, if you copy processing_forms.php to your local Web server, and run your browser with http://localhost/processing_forms.php?name=Joe, you will an error page like this:
You have submitted the following information:
Name = Joe
Comments =
Thank you!
PHP Notice: Undefined index:
comment in ...\processing_forms.php on line 3

27.

Where Is The Submitted Form Data Stored?

Answer»

When a user submit a FORM on your WEB server, user entered data will be TRANSFERRED to the PHP engine, which will make the submitted data available to your PHP script for PROCESSING in pre-defined ARRAYS:
• $_GET - An associate array that store form data submitted with the GET method.
• $_POST - An associate array that store form data submitted with the POST method.
• $_REQUEST - An associate array that store form data submitted with either GET or POST method. $_REQUEST also contains the cookie values received back from the browser.

When a user submit a form on your Web server, user entered data will be transferred to the PHP engine, which will make the submitted data available to your PHP script for processing in pre-defined arrays:
• $_GET - An associate array that store form data submitted with the GET method.
• $_POST - An associate array that store form data submitted with the POST method.
• $_REQUEST - An associate array that store form data submitted with either GET or POST method. $_REQUEST also contains the cookie values received back from the browser.

28.

How To Generate A Form?

Answer»

Generating a form seems to be easy. You can use PHP output statements to generate the required <FORM> tag and other input tags. But you should consider to organized your input fields in a table to make your form looks good on the screen. The PHP script below shows you a good example of HTML forms:
<?php
print("<html><form action=processing_forms.php method=post>");
print("<table><tr><TD colspan=2>Please ENTER and SUBMIT your"
." COMMENTS about PICKZYCenter.com:</td></tr>");
print("<tr><td>Your Name:</td>"
."<td><input type=text name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text name=comment></td></tr>\n");
print("<tr><td colspan=2><input type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you save this script as a PHP page, submit_comments.php, on your Web site, and view this page, you will see a simple Web form.

Generating a form seems to be easy. You can use PHP output statements to generate the required <FORM> tag and other input tags. But you should consider to organized your input fields in a table to make your form looks good on the screen. The PHP script below shows you a good example of HTML forms:
<?php
print("<html><form action=processing_forms.php method=post>");
print("<table><tr><td colspan=2>Please enter and submit your"
." comments about PICKZYCenter.com:</td></tr>");
print("<tr><td>Your Name:</td>"
."<td><input type=text name=name></td></tr>\n");
print("<tr><td>Comments:</td>"
."<td><input type=text name=comment></td></tr>\n");
print("<tr><td colspan=2><input type=submit><td></tr></table>\n");
print("</form></html>\n");
?>
If you save this script as a PHP page, submit_comments.php, on your Web site, and view this page, you will see a simple Web form.

29.

What Are Form Input Html Tags?

Answer»

HTML TAGS that can be used in a form to collect INPUT data are:
•<SUBMIT ...> - DISPLAYED as a button ALLOW USERS to submit the form.
•<INPUT TYPE=TEXT ...> - Displayed as an input field to take an input string.
•<INPUT TYPE=RADIO ...> - Displayed as a radio button to take an input flag.
•<INPUT TYPE=CHECKBOX ...> - Displayed as a checkbox button to take an input flag.
•<SELECT ...> - Displayed as a dropdown list to take input selection.
•<TEXTAREA ...> - Displayed as an input area to take a large amount of input text.

HTML tags that can be used in a form to collect input data are:
•<SUBMIT ...> - Displayed as a button allow users to submit the form.
•<INPUT TYPE=TEXT ...> - Displayed as an input field to take an input string.
•<INPUT TYPE=RADIO ...> - Displayed as a radio button to take an input flag.
•<INPUT TYPE=CHECKBOX ...> - Displayed as a checkbox button to take an input flag.
•<SELECT ...> - Displayed as a dropdown list to take input selection.
•<TEXTAREA ...> - Displayed as an input area to take a large amount of input text.

30.

How To Create A Web Form?

Answer»

If you take input data from visitors on your Web site, you can create a Web form with input fields to ALLOW visitors to fill in data and submit the data to your server for processing. A Web form can be created with the <FORM> tag with some input tags. The &AMP;FORM tag should be written in the FOLLOWING format:
<form action=processing.php method=get/post>
......
</form>
Where "processing.php" SPECIFIES the PHP page that PROCESSES the submitted data in the form.

If you take input data from visitors on your Web site, you can create a Web form with input fields to allow visitors to fill in data and submit the data to your server for processing. A Web form can be created with the <FORM> tag with some input tags. The &FORM tag should be written in the following format:
<form action=processing.php method=get/post>
......
</form>
Where "processing.php" specifies the PHP page that processes the submitted data in the form.

31.

How To Break A File Path Name Into Parts?

Answer»

If you have a file NAME, and want to get different parts of the file name, you can use the pathinfo() function. It breaks the file name into 3 parts: directory name, file base name and file extension; and returns them in an ARRAY. Here is a PHP script example on how to use pathinfo():
&LT;?php
$PATHNAME = "/temp/download/todo.txt";
$parts = pathinfo($pathName);
print_r($parts);
print("\n");
?&GT;
This script will print:
Array
(
[dirname] => /temp/download
[basename] => todo.txt
[extension] => txt
)

If you have a file name, and want to get different parts of the file name, you can use the pathinfo() function. It breaks the file name into 3 parts: directory name, file base name and file extension; and returns them in an array. Here is a PHP script example on how to use pathinfo():
<?php
$pathName = "/temp/download/todo.txt";
$parts = pathinfo($pathName);
print_r($parts);
print("\n");
?>
This script will print:
Array
(
[dirname] => /temp/download
[basename] => todo.txt
[extension] => txt
)

32.

How To Get The Directory Name Out Of A File Path Name?

Answer»

If you have the full path NAME of a file, and WANT to get the directory name portion of the path name, you can USE the dirname() function. It BREAKS the full path name at the last directory path delimiter (/) or (\), and returns the first portion as the directory name. Here is a PHP script example on how to use dirname():
<?php
$PATHNAME = "/temp/download/todo.txt";
$dirName = dirname($pathName);
print("File full path name: $pathName\n");
print("File directory name: $dirName\n");
print("\n");
?>
This script will print:
File full path name: /temp/download/todo.txt
File directory name: /temp/download

If you have the full path name of a file, and want to get the directory name portion of the path name, you can use the dirname() function. It breaks the full path name at the last directory path delimiter (/) or (\), and returns the first portion as the directory name. Here is a PHP script example on how to use dirname():
<?php
$pathName = "/temp/download/todo.txt";
$dirName = dirname($pathName);
print("File full path name: $pathName\n");
print("File directory name: $dirName\n");
print("\n");
?>
This script will print:
File full path name: /temp/download/todo.txt
File directory name: /temp/download

33.

How To Copy A File?

Answer»

If you have a FILE and WANT to make a COPY to create a NEW file, you can use the copy() function. Here is a PHP script example on how to use copy():
<?php
unlink("/temp/myPing.exe");
copy("/windows/system32/ping.exe", "/temp/myPing.exe");
if (file_exists("/temp/myPing.exe")) {
print("A copy of ping.exe is created.\n");
}
?>
This script will print:
A copy of ping.exe is created.

If you have a file and want to make a copy to create a new file, you can use the copy() function. Here is a PHP script example on how to use copy():
<?php
unlink("/temp/myPing.exe");
copy("/windows/system32/ping.exe", "/temp/myPing.exe");
if (file_exists("/temp/myPing.exe")) {
print("A copy of ping.exe is created.\n");
}
?>
This script will print:
A copy of ping.exe is created.

34.

How To Remove A File?

Answer»

If you WANT to remove an existing file, you can USE the unlink() function. Here is a PHP script example on how to use unlink():
&LT;?php
if (file_exists("/temp/todo.txt")) {
unlink("/temp/todo.txt");
print("File removed.\n");
} else {
print("File does not EXIST.\n");
}
?>
This script will print:
File removed.
If you run this script again, it will print:
File does not exist.

If you want to remove an existing file, you can use the unlink() function. Here is a PHP script example on how to use unlink():
<?php
if (file_exists("/temp/todo.txt")) {
unlink("/temp/todo.txt");
print("File removed.\n");
} else {
print("File does not exist.\n");
}
?>
This script will print:
File removed.
If you run this script again, it will print:
File does not exist.

35.

How To Remove An Empty Directory?

Answer»

If you have an empty existing directory and you want to remove it, you can use the rmdir(). Here is a PHP script example on how to use rmdir():
&LT;?php
if (file_exists("/temp/download")) {
rmdir("/temp/download");
PRINT("Directory removed.\n");
} else {
print("Directory does not EXIST.\n");
}
?&GT;
This script will print:
Directory removed.
If you run this script again, it will print:
Directory does not exist.

If you have an empty existing directory and you want to remove it, you can use the rmdir(). Here is a PHP script example on how to use rmdir():
<?php
if (file_exists("/temp/download")) {
rmdir("/temp/download");
print("Directory removed.\n");
} else {
print("Directory does not exist.\n");
}
?>
This script will print:
Directory removed.
If you run this script again, it will print:
Directory does not exist.

36.

How To Create A Directory?

Answer»

You can use the MKDIR() function to create a DIRECTORY. Here is a PHP script example on how to use mkdir():
&LT;?php
if (file_exists("/temp/download")) {
PRINT("Directory already exists.\n");
} else {
mkdir("/temp/download");
print("Directory created.\n");
}
?>
This script will print:
Directory created.
If you run this script again, it will print:
Directory already exists.

You can use the mkdir() function to create a directory. Here is a PHP script example on how to use mkdir():
<?php
if (file_exists("/temp/download")) {
print("Directory already exists.\n");
} else {
mkdir("/temp/download");
print("Directory created.\n");
}
?>
This script will print:
Directory created.
If you run this script again, it will print:
Directory already exists.

37.

How To Open Standard Output As A File Handle?

Answer»

If you want to open the standard OUTPUT as a file handle yourself, you can use the fopen("php://stdout") function. It CREATES a special file handle linking to the standard output, and returns the file handle. Once the standard output is opened to a file handle, you can use fwrite() to write data to the STARNDARD output like a regular file. Here is a PHP script example on how to write to standard output:
<?php
$stdout = fopen("php://stdout", "w");
fwrite($stdout,"To do:\n");
fwrite($stdout,"Looking for PHP hosting provider!\n");
fclose($stdout);
?>
This script will print:
What's your name?
To do:
Looking for PHP hosting provider!
If you don't want to open the standard output as a file handle yourself, you can use the constant STDOUT predefined by PHP as the file handle for standard output.
If you are using your script in a Web page, standard output is merged into the Web page HTML DOCUMENT.
print() and echo() also WRITES to standard output.

If you want to open the standard output as a file handle yourself, you can use the fopen("php://stdout") function. It creates a special file handle linking to the standard output, and returns the file handle. Once the standard output is opened to a file handle, you can use fwrite() to write data to the starndard output like a regular file. Here is a PHP script example on how to write to standard output:
<?php
$stdout = fopen("php://stdout", "w");
fwrite($stdout,"To do:\n");
fwrite($stdout,"Looking for PHP hosting provider!\n");
fclose($stdout);
?>
This script will print:
What's your name?
To do:
Looking for PHP hosting provider!
If you don't want to open the standard output as a file handle yourself, you can use the constant STDOUT predefined by PHP as the file handle for standard output.
If you are using your script in a Web page, standard output is merged into the Web page HTML document.
print() and echo() also writes to standard output.

38.

How To Read A File In Binary Mode?

Answer»

If you have a file that stores binary data, like an executable program or picture file, you need to READ the file in binary mode to ensure that none of the data gets modified during the reading process. You need to:
•Open the file with fopen($FILENAME, "rb").
•Read data with fread($fileHandle,$length).
Here is a PHP script EXAMPLE on reading binary file:
<?php
$in = fopen("/windows/system32/ping.exe", "rb");
$out = fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
$count++;
$BUFFER = fread($in,64);
FWRITE($out,$buffer);
}
fclose($out);
fclose($in);
print("About ".($count*64)." bytes read.\n");
?>
This script will print:
About 16448 bytes read.
This script actually copied an executable program file ping.exe in binary mode to new file. The new file should still be executable.

If you have a file that stores binary data, like an executable program or picture file, you need to read the file in binary mode to ensure that none of the data gets modified during the reading process. You need to:
•Open the file with fopen($fileName, "rb").
•Read data with fread($fileHandle,$length).
Here is a PHP script example on reading binary file:
<?php
$in = fopen("/windows/system32/ping.exe", "rb");
$out = fopen("/temp/myPing.exe", "w");
$count = 0;
while (!feof($in)) {
$count++;
$buffer = fread($in,64);
fwrite($out,$buffer);
}
fclose($out);
fclose($in);
print("About ".($count*64)." bytes read.\n");
?>
This script will print:
About 16448 bytes read.
This script actually copied an executable program file ping.exe in binary mode to new file. The new file should still be executable.

39.

How To Read One Character From A File?

Answer»

If you have a text file, and you want to read the file one character at a time, you can use the FGETC() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():
<?php
$file = fopen("/windows/system32/drivers/etc/services", "r");
$count = 0;
while ( ($CHAR=fgetc($file)) !== false ) {
if ($char=="/") $count++;
}
fclose($file);
print("Number of /: $count\n");
?>
This script will print:
Number of /: 113
NOTE that rtrim() is USED to remove "\n" from the returning string of fgets().

If you have a text file, and you want to read the file one character at a time, you can use the fgetc() function. It reads the current character, moves the file pointer to the next character, and returns the character as a string. If end of the file is reached, fgetc() returns Boolean false. Here is a PHP script example on how to use fgetc():
<?php
$file = fopen("/windows/system32/drivers/etc/services", "r");
$count = 0;
while ( ($char=fgetc($file)) !== false ) {
if ($char=="/") $count++;
}
fclose($file);
print("Number of /: $count\n");
?>
This script will print:
Number of /: 113
Note that rtrim() is used to remove "\n" from the returning string of fgets().

40.

How To Open A File For Writing?

Answer»

If you WANT to OPEN a new file and write date to the file, you can use the fopen($fileName, "w") function. It creates the SPECIFIED file, and returns a file handle. The SECOND argument "w" tells PHP to open the file for writing. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for writing:
&LT;?php
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n");
fclose($file);
?>
This script will write the following to the file:
Download PHP scripts at dev.pickzycenter.com.
Note that you should use "\r\n" to terminate lines on Windows. On a Unix system, you should use "\n".

If you want to open a new file and write date to the file, you can use the fopen($fileName, "w") function. It creates the specified file, and returns a file handle. The second argument "w" tells PHP to open the file for writing. Once the file is open, you can use other functions to write data to the file through this file handle. Here is a PHP script example on how to use fopen() for writing:
<?php
$file = fopen("/temp/todo.txt", "w");
fwrite($file,"Download PHP scripts at dev.pickzycenter.com.\r\n");
fclose($file);
?>
This script will write the following to the file:
Download PHP scripts at dev.pickzycenter.com.
Note that you should use "\r\n" to terminate lines on Windows. On a Unix system, you should use "\n".

41.

How To Open A File For Reading?

Answer»

If you want to open a file and READ its contents piece by piece, you can use the fopen($fileName, "r") function. It opens the SPECIFIED file, and returns a file handle. The second argument "r" TELLS PHP to open the file for reading. Once the file is open, you can use other functions to read data from the file through this file handle. Here is a PHP script example on how to use fopen() for reading:
<?php
$file = fopen("/windows/system32/drivers/etc/hosts", "r");
PRINT("Type of file handle: " . gettype($file) . "\N");
print("The first line from the file handle: " . fgets($file));
fclose($file);
?>
This script will print:
Type of file handle: resource
The first line from the file handle: # Copyright (c) 1993-1999
Note that you should always call fclose() to close the opened file when you are done with the file.

If you want to open a file and read its contents piece by piece, you can use the fopen($fileName, "r") function. It opens the specified file, and returns a file handle. The second argument "r" tells PHP to open the file for reading. Once the file is open, you can use other functions to read data from the file through this file handle. Here is a PHP script example on how to use fopen() for reading:
<?php
$file = fopen("/windows/system32/drivers/etc/hosts", "r");
print("Type of file handle: " . gettype($file) . "\n");
print("The first line from the file handle: " . fgets($file));
fclose($file);
?>
This script will print:
Type of file handle: resource
The first line from the file handle: # Copyright (c) 1993-1999
Note that you should always call fclose() to close the opened file when you are done with the file.

42.

How To Read The Entire File Into A Single String?

Answer»

If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It OPENS the SPECIFIED file, reads all characters in the file, and RETURNS them in a single string. Here is a PHP script example on how to file_get_contents():
<?php
$file = file_get_contents("/windows/system32/drivers/etc/services");
print("Size of the file: ".strlen($file)."\N");
?>
This script will print:
Size of the file: 7116

If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():
<?php
$file = file_get_contents("/windows/system32/drivers/etc/services");
print("Size of the file: ".strlen($file)."\n");
?>
This script will print:
Size of the file: 7116

43.

How To Define A Function With Any Number Of Arguments?

Answer»

If you want to define a FUNCTION with any number of arguments, you need to:
•Declare the function with no argument.
•Call func_num_args() in the function to get the number of the arguments.
•Call func_get_args() in the function to get all the arguments in an array.
Here is a PHP SCRIPT on how to handle any number of arguments:
<?php
function myAverage() {
$COUNT = func_num_args();
$args = func_get_args();
$sum = array_sum($args);
return $sum/$count;
}
$AVERAGE = myAverage(102, 121, 105);
print("Average 1: $average\n");
$average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114);
print("Average 2: $average\n");
?>
This script will print:
Average 1: 109.33333333333
Average 2: 107.66666666667

If you want to define a function with any number of arguments, you need to:
•Declare the function with no argument.
•Call func_num_args() in the function to get the number of the arguments.
•Call func_get_args() in the function to get all the arguments in an array.
Here is a PHP script on how to handle any number of arguments:
<?php
function myAverage() {
$count = func_num_args();
$args = func_get_args();
$sum = array_sum($args);
return $sum/$count;
}
$average = myAverage(102, 121, 105);
print("Average 1: $average\n");
$average = myAverage(102, 121, 105, 99, 101, 110, 116, 101, 114);
print("Average 2: $average\n");
?>
This script will print:
Average 1: 109.33333333333
Average 2: 107.66666666667

44.

How To Specify Argument Default Values?

Answer»

If you want to ALLOW the caller to skip an argument when calling a function, you can define the argument with a default VALUE when defining the function. Adding a default value to an argument can be done like this "function name($arg=expression){}. Here is a PHP script on how to specify default values to ARGUMENTS:
<?php
function printKey($KEY="download") {
print("PHP $key\n");
}
printKey();
printKey("hosting");
print("\n");
?>
This script will print:
PHP download
PHP hosting

If you want to allow the caller to skip an argument when calling a function, you can define the argument with a default value when defining the function. Adding a default value to an argument can be done like this "function name($arg=expression){}. Here is a PHP script on how to specify default values to arguments:
<?php
function printKey($key="download") {
print("PHP $key\n");
}
printKey();
printKey("hosting");
print("\n");
?>
This script will print:
PHP download
PHP hosting

45.

How To Access A Global Variable Inside A Function?

Answer»

By DEFAULT, global variables are not ACCESSIBLE inside a function. However, you can MAKE them accessible by declare them as "global" inside a function. Here is a PHP SCRIPT on declaring "global" variables:
<?php
?>
$intRate = 5.5;
function myAccount() {
global $intRate;
print("Defined inside the function? ". isset($intRate)."\n");
}
myAccount();
print("Defined outside the function? ". isset($intRate)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function? 1

By default, global variables are not accessible inside a function. However, you can make them accessible by declare them as "global" inside a function. Here is a PHP script on declaring "global" variables:
<?php
?>
$intRate = 5.5;
function myAccount() {
global $intRate;
print("Defined inside the function? ". isset($intRate)."\n");
}
myAccount();
print("Defined outside the function? ". isset($intRate)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function? 1

46.

What Is The Scope Of A Variable Defined Outside A Function?

Answer»

A VARIABLE defined OUTSIDE any functions in main script body is called global variable. However, a global variable is not really accessible globally any in the script. The scope of global variable is LIMITED to all statements outside any functions. So you can not access any global VARIABLES inside a function. Here is a PHP script on the scope of global variables:
<?php
?>
$login = "pickzycenter";
function myLogin() {
print("Defined inside the function? ". isset($login)."\N");
}
myLogin();
print("Defined outside the function? ". isset($login)."\n");
?>
This script will print:
Defined inside the function?
Defined outside the function? 1

A variable defined outside any functions in main script body is called global variable. However, a global variable is not really accessible globally any in the script. The scope of global variable is limited to all statements outside any functions. So you can not access any global variables inside a function. Here is a PHP script on the scope of global variables:
<?php
?>
$login = "pickzycenter";
function myLogin() {
print("Defined inside the function? ". isset($login)."\n");
}
myLogin();
print("Defined outside the function? ". isset($login)."\n");
?>
This script will print:
Defined inside the function?
Defined outside the function? 1

47.

What Is The Scope Of A Variable Defined In A Function?

Answer»

The scope of a LOCAL variable defined in a FUNCTION is limited with that function. Once the function is ended, its local variables are also removed. So you can not ACCESS any local variable outside its defining function. Here is a PHP script on the scope of local variables in a function:
<?php
?&GT;
function myPassword() {
$password = "U8FIE8W0";
print("Defined inside the function? ". isset($password)."\N");
}
myPassword();
print("Defined outside the function? ". isset($password)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function?

The scope of a local variable defined in a function is limited with that function. Once the function is ended, its local variables are also removed. So you can not access any local variable outside its defining function. Here is a PHP script on the scope of local variables in a function:
<?php
?>
function myPassword() {
$password = "U8FIE8W0";
print("Defined inside the function? ". isset($password)."\n");
}
myPassword();
print("Defined outside the function? ". isset($password)."\n");
?>
This script will print:
Defined inside the function? 1
Defined outside the function?

48.

Can You Define An Array Argument As A Reference Type?

Answer»

You can define an ARRAY argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an array argument as a reference type:
<?php
function ref_shrink(&$array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before SHRINKING: ".join(",",$numbers)."\n");
ref_shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
BBEFORE shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5

You can define an array argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an array argument as a reference type:
<?php
function ref_shrink(&$array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
ref_shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
BBefore shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5

49.

How Arrays Are Passed Through Arguments?

Answer»

Like a normal variable, an ARRAY is passed through an argument by value, not by REFERENCE. That means when an array is passed as an argument, a copy of the array will be passed into the function. Modipickzyng that copy INSIDE the function will not impact the original copy. Here is a PHP script on passing arrays by values:
<?php
function shrink($array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\N");
shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5,7,6,2,1,3,4,2
As you can SEE, original variables were not affected.

Like a normal variable, an array is passed through an argument by value, not by reference. That means when an array is passed as an argument, a copy of the array will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing arrays by values:
<?php
function shrink($array) {
array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5,7,6,2,1,3,4,2
As you can see, original variables were not affected.

50.

Can You Pass An Array Into A Function?

Answer»

You can pass an ARRAY into a function in the same as a normal variable. No special syntax needed. Here is a PHP script on how to pass an array to a function:
&LT;?php
function AVERAGE($array) {
$sum = array_sum($array);
$count = count($array);
return $sum/$count;
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Average: ".average($numbers)."\n");
?>
This script will print:
Average: 3.75

You can pass an array into a function in the same as a normal variable. No special syntax needed. Here is a PHP script on how to pass an array to a function:
<?php
function average($array) {
$sum = array_sum($array);
$count = count($array);
return $sum/$count;
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Average: ".average($numbers)."\n");
?>
This script will print:
Average: 3.75