The document discusses creating and managing HTML forms with PHP. It covers creating a basic HTML form with tags like <form> and <input>, then processing the form data with a PHP script. The PHP script receives submitted data through superglobal variables like $_POST and $_GET. Form validation is also covered, using functions like empty() and conditionals to check for required fields and proper data formats. The document also discusses arrays in PHP for storing multiple submitted values, and using foreach loops to access array elements.
PHP is one of the simplest server-side languages out there, and it was designed primarily for web development. Learning PHP is good not only because it adds ...
PHP is one of the simplest server-side languages out there, and it was designed primarily for web development. Learning PHP is good not only because it adds ...
All variables in PHP start with a $ (dollar) sign followed by the name of the variable.
A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores.
If a variable name is more than one word, it can be separated with underscore (for example $employee_code instead of $employeecode).
'$' is a special variable that can not be assigned.
Correctly understanding the eight data types in PHP is essential to a solid foundation in development. Come refresh your knowledge of the scalar types, compound types, and special data types used in PHP, and learn about proper usage of each. Review type juggling, learn some common data type traps to avoid, and how to code defensively to prevent having the data type of a variable change unexpectedly. Finally learn how unit tests can help verify that code is handling data types correctly.
The New Customer Engagement.
OPINATOR facilitates high value interactions between businesses and customers as never seen before.
OPIANTOR uses Artificial Intelligence software to identify the customer sentiment and acts in real time to maximize the customer experience and therefore, the link between the customer and the business. All in an unseen way.
Come and discover OPINATOR, the New Marketing and Customer Engagement!
All variables in PHP start with a $ (dollar) sign followed by the name of the variable.
A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores.
If a variable name is more than one word, it can be separated with underscore (for example $employee_code instead of $employeecode).
'$' is a special variable that can not be assigned.
Correctly understanding the eight data types in PHP is essential to a solid foundation in development. Come refresh your knowledge of the scalar types, compound types, and special data types used in PHP, and learn about proper usage of each. Review type juggling, learn some common data type traps to avoid, and how to code defensively to prevent having the data type of a variable change unexpectedly. Finally learn how unit tests can help verify that code is handling data types correctly.
The New Customer Engagement.
OPINATOR facilitates high value interactions between businesses and customers as never seen before.
OPIANTOR uses Artificial Intelligence software to identify the customer sentiment and acts in real time to maximize the customer experience and therefore, the link between the customer and the business. All in an unseen way.
Come and discover OPINATOR, the New Marketing and Customer Engagement!
The New Customer Engagement.
OPINATOR facilitates high value interactions between businesses and customers as never seen before.
OPIANTOR uses Artificial Intelligence software to identify the customer sentiment and acts in real time to maximize the customer experience and therefore, the link between the customer and the business. All in an unseen way.
Come and discover OPINATOR, the New Marketing and Customer Engagement!
PHP: Why PHP and MySQL? Server-side scripting, PHP syntax and variables, comments, types, control structures, branching, looping, termination, functions, passing information with PHP, GET, POST, formatting form variables, superglobal arrays, strings and string functions, regular expressions, arrays, number handling, basic PHP errors/problems
This PPT gives the details about Introduction, Syntax, Comments, Case Sensitivity,Variables,Data Types, Strings, Constants,Operators,Control Flow Statements,Functions,Arrays
, and Forms
Vision Academy – Training Institute in Pune is a pioneer in training Institutes providing various professional training courses for multiple technologies. Proficient professionals and experts constitute an institute. We are working on technological domains as a centre for education to give a comprehensive and most exceptional learning experience in various technologies. Vision Academy is the Leading Professional Training Institute for SEO, Digital Marketing Courses in Pune. We also offer other IT Training’s like AngularJS, MVC, Python, Salesforce, Data Science, AI, Blockchain Hadoop, RPA (Blue Prism, Automation Anywhere, and UI Path) Informatics, Selenium. Our Specialty is that we provide Hands-on Training for all Courses, and All Trainers at our Institute are from MNC’s.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
1. Creating HTML Forms
Pengaturcaraan PHP
Managing HTML forms with PHP is a two-step process. First, you create
the HTML form itself, using any text or WYSIWYG editor you choose. Then,
you create the corresponding PHP script that will receive and process the
form data. An HTML form is created using the form tags and various input
types. The form tags look as follows:
The most important attribute of your form tag is action, which dictates to
which page the form data will be sent. The second attribute — method —
has its own issues, but post is the value you'll use most frequently.
1
2. Pengaturcaraan PHP
Choosing a Method
The method attribute of a form dictates how the data is sent to the
handling page. The two options — get and post — refer to the HTTP
(Hypertext Transfer Protocol) method to be used. In short, the get
method sends the submitted data to the receiving page as a series of
name-value pairs appended to the URL.
Consider the example shown below:
Pengaturcaraan PHP
The benefit of using the get method
is that the resulting page can be
bookmarked in the user's Web
browser (since it's a URL). For that
matter, you can also click Back in
your Web browser to return to a get
page, or reload it without problem
(neither of which is true for post).
Unfortunately, you are limited to how
much data can be transmitted via get
and it's less secure (since the data is
visible).
2
7. Pengaturcaraan PHP
Once you have an HTML form, the next step is to write a bare-
bones PHP script to handle it. When we say that this script will be
handling the form, we mean that it will do something with the
data it receives; that is it will reiterate the data back to the Web
browser.
The PHP page that receives the form data will assign what the user
entered into this form element to a special variable called
$_REQUEST['weight']. It is very important that the spelling and
capitalization match exactly, as PHP is case-sensitive when it comes to
variable names. $_REQUEST['weight'] can then be used like any other
variable: printed, used in mathematical computations, concatenated, and
so on.
Pengaturcaraan PHP
Registering Globals
In earlier versions of PHP, the
register_globals setting was turned on by
default. This feature gave PHP an ease of
use by automatically turning form inputs
into similarly named variables, like $name
or $email (as opposed to having to refer
to $_REQUEST['name'] and
$_REQUEST['email'] first).
As of version 4.2 of PHP, the
developers behind PHP opted to turn this
setting off by default because not relying
on this feature improves the security
of your scripts. Unfortunately, this also To work around this, there are two
had the side effect that a lot of existing options. First, you could turn
scripts no longer worked and many
beginning programmers were stymied
register_globals back on, assuming
when they saw blank values in their that you have administrative control
form results, error messages, or just over your PHP installation. Second,
blank pages. you could start using the
superglobal variables, such as
$_REQUEST, $_GET, and $_POST.
7
8. Pengaturcaraan PHP
Pengaturcaraan PHP
Following the rules outlined before, the data entered into the name form
input, which has a name value of name, will be accessible through the
variable $_REQUEST['name']. The data entered into the email form input,
which has a name value of email, will be accessible through
$_REQUEST['email']. The same applies to the entered comments data.
Again, the spelling and capitalization of your variables here must exactly
match the corresponding name values in the HTML form.
8
10. Pengaturcaraan PHP
Pengaturcaraan PHP
$_REQUEST
$_REQUEST is a special variable type in PHP, available since version
4.1. It stores all of the data sent to a PHP page through either the GET
or POST methods, as well as data accessible in cookies.
Blank pages
If you see a blank page after submitting the form, first check the
HTML source to look for HTML errors, and then confirm that
display_errors is on in your PHP configuration.
10
11. Pengaturcaraan PHP
Others way to avoid _$_REQUEST[‘variable’]
extract($_GET);
extract($_POST);
extract($_COOKIE);
User can call directly the name of variable like $name without using
the method $_POST[“name”].
Managing Magic Quotes
11
13. Pengaturcaraan PHP
In PHP there are two main types of Magic Quotes: magic_quotes_gpc,
which applies to form, URL, and cookie data (gpc stands for get, post,
cookie); and magic_quotes_runtime, which applies to data retrieved
from external files and databases. If Magic Quotes is enabled on your
server, you can undo its effect using the stripslashes() function.
This function will remove any backslashes found in $var.
Pengaturcaraan PHP
13
14. Pengaturcaraan PHP
Pengaturcaraan PHP
addslashes() function
You can emulate what Magic Quotes does if it's disabled by using the
opposite of the stripslashes() function, addslashes().
trim() function
When working with strings stemming from forms, it's also a good idea to
use the trim() function, which removes excess white spaces from
both ends of the value.
$name = trim($name);
14
15. Conditionals
Pengaturcaraan PHP
Conditionals, like variables, are integral to programming, and most people are
familiar with them in some form or another. Dynamic Web pages, as you might
imagine, frequently require the use of conditionals to alter a script's behavior
according to set criteria.
PHP's three primary terms for creating conditionals are if, else, and elseif
(which can also be written as two words, else if).
Every conditional includes an if clause, as shown here.
15
16. Pengaturcaraan PHP
The if clause in turn can specify an
alternate course of action by using else.
It can also be written to include
another condition and a couple of
alternatives by using elseif and else,
as in this example.
Pengaturcaraan PHP
If a condition is true, the code in the
following curly braces ({}) will be
executed. If not, PHP will continue on.
If there is a second condition (after an
elseif), that will be checked for truth.
The process will continue — you can
use as many elseif clauses as you
want — until PHP hits an else, which
will be automatically executed at that
point, or until the conditional
terminates without an else.
For this reason, it's important that the
else always come last and be treated
as the default action unless specific
criteria (the conditions)
16
17. In the second example, a new function, isset(), is introduced. This function
checks if a variable is set, meaning that it has a value other than NULL.
You can also use the comparative and logical operators, listed in the table
below, in conjunction with parentheses to make more complicated expressions.
SYMBOL MEANING TYPE EXAMPLE
$x == $y
== is equal to comparison
!= $x ! = $y
is not equal to comparison
$x < $y
< less than comparison
$x > $y
> greater than comparison
$x <= $y
<= less than or equal to comparison
$x >= $y
>= greater than or equal to comparison
! !$x
not logical
$x && $y
&& and logical
|| or logical $x || $y
XOR and not logical $x XOR $y
Pengaturcaraan PHP
17
18. Pengaturcaraan PHP
This is a simple and effective way to validate a form input
(particularly a radio button, check box, or select). If the user checks either
gender radio button, then $_REQUEST['gender'] will have a value, meaning
that the condition isset($_REQUEST['gender']) is true. In such a case, the
shorthand version of this variable — $gender — is assigned the value of
$_REQUEST['gender'], repeating the technique used with $name, $email,
and $comments.
If the condition is not true, then $gender is assigned the value of NULL,
indicating that it has no value. Notice that NULL is not in quotes.
Pengaturcaraan PHP
18
19. Pengaturcaraan PHP
This if-elseif-else conditional looks at the value of the $gender variable and
prints a different message for each possibility. It's very important to
remember that the double equals sign (==) means equals, whereas a single
equals sign (=) assigns a value.
The distinction is important because the condition $gender == 'M' may or
may not be true, but $gender = 'M' will always be true.
Pengaturcaraan PHP
19
20. Pengaturcaraan PHP
Switch
PHP has another type of conditional, called the
switch, best used in place of a long if-elseif-else
conditional. The syntax of switch is shown here.
The switch conditional compares the value of
$variable to the different cases. When it finds a
match, the following code is executed, up until
the break. If no match is found, the default is
executed, assuming it exists (it's optional).
The switch conditional is limited in its usage in that
it can only check a variable's value for equality
against certain cases; more complex conditions
cannot be easily checked.
Pengaturcaraan PHP
20
21. Validating Form Data
Pengaturcaraan PHP
Validating form data requires
the use of conditionals and
any number of functions,
operators, and expressions.
One common function to be
used is isset(), which tests if
a variable has a value
(including 0, FALSE, or an
empty string, but not NULL).
To check that a user typed something into textual elements like name,
email, and comments, you can use the empty() function. It checks if a
variable has an empty value — an empty string, 0, NULL, or FALSE.
21
22. Pengaturcaraan PHP
The first aim of form validation is ensuring that something was entered or
selected in form elements. The second goal is to ensure that submitted data is
of the right type (numeric, string, etc.), of the right format (like an email
address), or a specific acceptable value (like $gender being equal to either M
or F).
Next, let's write a new handle_form.php script that makes sure variables have
values before they're referenced.
Pengaturcaraan PHP
22
25. Pengaturcaraan PHP
strlen() function
Another way of validating text inputs is to use the strlen() function to see if
more than zero characters were typed.
if (strlen($var) > 0) {
// $var has a value.
} else {
// $var does not have a value.
}
Arrays
25
26. Pengaturcaraan PHP
Unlike strings and numbers (which are scalar variables, meaning they can
store only a single value at a time), an array can hold multiple, separate
pieces of information. An array is therefore like a list of values, each value
being a string or a number or even another array.
Arrays are structured as a series of key-value pairs, where one pair is an
item or element of that array. For each item in the list, there is a key (or
index) associated with it. The resulting structure is not unlike a spreadsheet
or database table.
PHP supports two kinds of arrays. The first type, called indexed arrays, uses
numbers as the keys, as in the first example, the $artists array. As in most
programming languages, with indexed arrays, your arrays will begin with the
first index at 0, unless you specify the keys explicitly.
Key Value
0 Low
1 Aimee Mann
2 Ani DiFranco
3 Spiritualized
The second type of array, associative, uses strings as keys as in the
following example. The $states array uses the state abbreviation for its
keys.
Key Value
MD Maryland
PA Pennsylvania
IL Illinois
MO Missouri
26
27. Pengaturcaraan PHP
An array follows the same naming rules as any other variable. So offhand,
you might not be able to tell that $var is an array as opposed to a string or
number. The important syntactical difference has to do with accessing
individual array elements.
To retrieve a specific value from an array, you refer to the array name first,
followed by the key, in square brackets:
Pengaturcaraan PHP
Because arrays use a different syntax than other variables, printing them can be
trickier. First, since an array can contain multiple values, you cannot use a
simple print statement.
Second, the keys in associative arrays complicate printing them and cause a
parse error.
27
28. Pengaturcaraan PHP
To work around this, wrap your array name and key in curly braces when your
array uses strings for its keys.
Numerically indexed arrays don't have this problem.
Superglobal Arrays
PHP includes several predefined arrays by default. These are the superglobal
variables — $_GET, $_POST, $_SESSION, $_REQUEST, $_SERVER,
$_COOKIE, and so forth, added to PHP as of version 4.1.
The $_GET variable is where PHP stores all of the variables and values sent to a
PHP script via the get method (presumably but not necessarily from an HTML
form). $_POST stores all of the data sent to a PHP script from an HTML form
that uses the post method. Both of these — along with $_COOKIE — are
subsets of $_REQUEST.
The superglobals have two benefits over registered global variables. First,
they are more secure because they are more precise (they indicate where the
variable came from). Second, they are global in scope (hence the name). If you
find the syntax of these variables to be confusing, you can use the shorthand
technique at the top of your scripts as follows:
28
30. Pengaturcaraan PHP
Pengaturcaraan PHP
Earlier versions of PHP
The superglobals are new to PHP as of version 4.1. If you are using an
earlier version of the language, use $HTTP_POST_VARS instead of
$_POST, and $HTTP_GET_VARS instead of $_GET.
30
31. Creating and Accessing
Arrays
Pengaturcaraan PHP
Creating Arrays
Although you can use PHP-generated
arrays, there will frequently be times
when you want to create your own.
There are two primary ways to define
your own array. First, you could add
one element at a time to build one,
as in this example.
It's important to understand that if
you specify a key and a value already
exists indexed with that same key, the
new value will overwrite the existing
one. In this example, based on the
latest assignment, the value of
$array['son'] is Michael and that of
array[2] is orange.
31
32. Pengaturcaraan PHP
Instead of adding one element at a time, you can use the array() function to
build an entire array in one step.
This function can be used whether or not you explicitly set the key.
Pengaturcaraan PHP
On the other hand, if you set the first numeric key value, the added
values will be keyed incrementally thereafter, as in this example.
Finally, if you want to create an array of sequential numbers you can use the
range() function.
32
33. Accessing Arrays
Individual array elements can be accessed by key (e.g., $_POST['email']). This
works when you know exactly what the keys are or if you want to refer to only a
single element. To access every array element, use the foreach loop.
The foreach loop will iterate through every element in $array, assigning each
element's value to the $value variable. In this example, you can access both
the keys and values.
Pengaturcaraan PHP
33
36. Pengaturcaraan PHP
count() or sizeof() function
To determine the number of elements in an array, use the count() or
sizeof() function (the two are synonymous):
$num=count($array);
range() function
The range() function can also create an array of sequential letters as
of PHP 4.1:
$alphabet=range('a','z');
Error message in foreach loop
If you see an 'Invalid argument supplied for foreach()' error
message, that means you are trying to use a foreach loop on a variable
that is not an array.
Multidimensional
Arrays
36
37. Pengaturcaraan PHP
An array's values could be any combination of numbers, strings, and even
other arrays. This last option — an array consisting of other arrays — creates
a multidimensional array.
Multidimensional arrays are much more common than you might expect
(especially if you use the superglobals) but remarkably easy to work with. As
an example, let's say you have an array called $states and another one called
$provinces for Canada, both created by the following definitions.
Pengaturcaraan PHP
These two arrays could be combined into one multidimensional array as
follows:
37
38. Pengaturcaraan PHP
To access the $states array, you refer to $abbr['US']
To access Maryland, use $abbr['US']['MD']
Of course, you can still access multidimensional arrays
using the foreach loop, nesting one inside another if
necessary.
Pengaturcaraan PHP
To print out one of these values, surround the whole construct in curly
braces:
38
45. Pengaturcaraan PHP
$_POST['interests']
Even if the user selects only one interest, $_POST['interests'] will still be
an array because the HTML name for the corresponding input is interests[]
(the square brackets make it an array).
select menu
You can also end up with a multidimensional array by having an HTML
form's select menu allow for multiple selections:
‹select name="interests[]" multiple="multiple"›
‹option value="Music"›Music‹/option›
‹option value="Movies"›Movies‹/option›
‹option value="Books"›Books‹/option›
‹option value="Skiing"›Skiing‹/option›
‹option value="Napping"›Napping‹/option›
‹/select›
Arrays and Strings
45
46. Pengaturcaraan PHP
Because strings and arrays are so commonly used, PHP has two functions
for converting between these two variable types.
The key to using and understanding these two functions is the separator and
glue relationships. When turning an array into a string, you set the glue —
the characters or code that will be inserted between the array values in the
generated string. Conversely, when turning a string into an array, you specify
the separator, which is the code that delineates between the different elements
in the generated array.
Let's examine some examples.
Pengaturcaraan PHP
The $days_array variable is
now a five-element array,
with Mon indexed at 0, Tue
indexed at 1, etc.
The $string2 variable is now
a comma-separated list of
days — Mon, Tue, Wed,
Thurs, Fri.
46
49. Sorting Arrays
Pengaturcaraan PHP
One of the many advantages arrays have over the other variable types is
the ability to sort them. PHP includes several functions you can use for
sorting arrays, all simple in syntax.
49
50. Pengaturcaraan PHP
Array (sort/rsort)
Sorting Array :
sort($pantry_food); - Sort with ascending 0 - 9
rsort($pantry_food); - Sort with Descending 9 – 0
Sort with alphabet alphabet
asort($pantry_food); - Sort with ascending A - Z
arsort($pantry_food); - Sort with Descending Z – A
Pengaturcaraan PHP
50
52. Pengaturcaraan PHP
Pengaturcaraan PHP
Array (Adding/Replace)
In array, we can add or change content of array
example 1 :
$fruit = array('banana','papaya');
Cara menambah :
<? $fruit[2] = “apple”;
print “$fruit[2] ?>
The Output
apple
52
53. Pengaturcaraan PHP
Array (merging)
You also can merge 2 or more array.
Example 1 :
$pantry = array(
1 => "apples",
2 => "oranges",
3 => "bananas"
);
$pantry2 = array(
1 => "potatoes",
2 => "bread",
3 => "tomatoes"
);
Pengaturcaraan PHP
Array (Merging)
Way to combine :
<?
$pantry_food = array_merge ($pantry, $pantry2);
?>
The Output
$pantry_food[0] = "apples";
$pantry_food[1] = "oranges";
$pantry_food[2] = "bananas";
$pantry_food[3] = "potatoes";
$pantry_food[4] = "bread";
$pantry_food[5] = "tomatoes";
53
54. Pengaturcaraan PHP
Array (push)
The way to add content at the last of array elemt :
example
$pantry = array(
1 => "tomatoes",
0 => "oranges",
4 => "bananas",
3 => "potatoes",
2 => "bread"
);
array_push($pantry, "apples");
For and While Loops
54
55. Two types of loops you'll use when managing arrays are for and while.
Consider the example of while loop.
As long as the condition part of the loop is true, the loop will be executed.
Once it becomes false, the loop is stopped. If the condition is never true, the
loop will never be executed. The while loop will most frequently be used
when retrieving results from a database.
Pengaturcaraan PHP
The for loop has a more complicated syntax.
Upon first executing the loop, the initial expression is run. Then the condition
is checked and, if true, the contents of the loop are executed. After execution,
the closing expression is run and the condition is checked again. This
process continues until the condition is false. Again, the loop will never be
executed if the condition is never true.
55
56. Pengaturcaraan PHP
Consider this example.
The first time this loop is run, the $i variable is set to the value of 1. Then
the condition is checked (is 1 less than or equal to 10?). Since this is
true, 1 is printed out (echo $i). Then, $i is incremented to 2 ($i++), the
condition is checked, and so forth. The result of this script will be the
numbers 1 through 10 printed out.
Pengaturcaraan PHP
56
59. Pengaturcaraan PHP
String – “strtok”
To take a certain char in the one sentence. The way to take the char can
use “,” “.” or anything else
Sntax “strtok(“variable",“condition");”
Example :
<?php
$bigstring = "BigBad Wolf";
$firstpart = strtok($bigstring," ");
echo "$firstpart";
?>
The output
BigBad
Pengaturcaraan PHP
String – “substr”
To take the char based on position. It start from left and counting start by 0
Syntax “substr(“variable",position,length);”
Example :
<?php
$bigstring = "BigBad Wolf";
$example = substr($bigstring,7,4);
echo "$example";
?>
The output
Wolf
59
60. Pengaturcaraan PHP
String – “eregi/ereg”
To search char in variable. Ereg only can search based on case sensitive
saja.
eregi can search without concern about case-sensitive
Syntax “ereg(“condition",“variable");”
Syntax “eregi(“condition",“variable");”
Pengaturcaraan PHP
Example ereg
$pattern = "z";
$search_area = "My car goes ZOOM.";
$search_result = ereg($pattern,$search_area);
if ($search_result){
// print this if there is a true result.
echo "Success, the pattern was found!";
} else {
// print this if there is a false result.
echo "Failure, the pattern was not found!";
}
Output
Failure, the pattern was not found!
60
61. Pengaturcaraan PHP
Example eregi
$pattern = "z";
$search_area = "My car goes ZOOM.";
$search_result = eregi($pattern,$search_area);
if ($search_result){
// print this if there is a true result.
echo "Success, the pattern was found!";
} else {
// print this if there is a false result.
echo "Failure, the pattern was not found!";
}
Output
Success, the pattern was found!
Pengaturcaraan PHP
String – “str_replace”
Syntax “str_replace(",","", “variable");”
To change anything (like coma) to the anything (like $ dollar sign)
Contoh :
$cfcost1 = “2,300.00”;
$cfcost1 = str_replace(",","","$cfcost1");
Output :
2300.00
61
62. Pengaturcaraan PHP
String – “eregi_replace”
To replace char in variable based on search
Syntax: eregi_replace(pattern,replacement,search_area);
Example
$entry = “user@yahoo.com
$pattern = “@";
$replacement = “(a)";
$entry = ereg_replace($pattern,$replacement,$entry);
echo "$entry";
output
user(a)yahoo.com
Pengaturcaraan PHP
String - “strlen”
To count total of char in the variable value
Syntax “strlen(“variable")”
Example :
if(strlen($password) < 6)
{
print “Jumlah password anda kurang dari 6 aksara”;
}
else
{
print “Tahniah”;
}
62
63. Pengaturcaraan PHP
String - “strstr”
To search certain value in variable
Syntax “strstr(“variable“,”word to search”)”
Example :
$member = “pAB7”;
if(strstr($member,”AB”))
{
print “Membership anda akan luput tidak lama lagi”;
}
else
{
print “Tahniah”;
}
Pengaturcaraan PHP
String - “trim”
To clear any blank space in variable at the beginning and end
Syntax “trim(“variable“)”
Example :
$member = “ pAB7 ”;
$member = trim($member)
print “$member”;
Output
// print “pAB7”;
63
64. Pengaturcaraan PHP
String - “rtrim”
To clear any blank space at the end of variable
Syntax “trim(“variable“)”
Example :
$member = “ pAB7 ”;
$member = trim($member)
print “$member”;
Output
// print “ pAB7”;
Pengaturcaraan PHP
String - “ltrim”
To clear any blank space and the begging of variable
Syntax “ltrim(“variable“)”
Example :
$member = “ pAB7 ”;
$member = trim($member)
print “$member”;
Output
// print “pAB7 ”;
64
65. Pengaturcaraan PHP
String - “substr_replace”
The function same with substr() but it can change the content of variable
syntax “substr_replace(“variable“,”Word To Replace”, position, length)”
Contoh :
$member = “mz02xyz”;
$member = substr_replace($member, “03”, 2, 2)
print “$member”;
Output
// print “mz03xyz”;
Pengaturcaraan PHP
String - “str_repeat”
To repeat the sentence follow by total of number required
Syntax “str_repeat($string, $n)” : repeat $string $n times
Example :
echo str_repeat('*', 10);
Output
// print “***********”;
65
66. Pengaturcaraan PHP
String - “strtoupper”
To convert variable to UPPER CASE
Syntax “strtoupper(“variable”)”
Example :
$member = “mzxyz”;
$member =strtoupper($member)
print “$member”;
Output
// print “MZXYZ”;
Pengaturcaraan PHP
String - “strtolower”
To convert variable to lowercase
Syntax “strtolower(“variable”)”
Example :
$member = “MZXYZ”;
$member =strtoupper($member)
print “$member”;
Output
// print “mzxyz”;
66
67. Pengaturcaraan PHP
String - “strrchr”
To get the value of the end of variable with condition
Syntax “strrchr(“variable”, “aksara”) ”
Example :
$file = “file.php”;
$ext = $ext = substr(strrchr($file, '.'), 1);
print “$ext”;
Output
// print “php”;
Pengaturcaraan PHP
String - “wordwrap()”
To display variable with the smart appearance which the default can set
Syntax “wordwrap(“variable”,”panjang sesuatu ayat”)”
Example :
$string = “Malaysia negara maju, aman, makmur dan sentoasa”;
$string .= “Terdiri daripada 14 buah negeri dan sebuah kerajaan
persekutuann”;
echo wordwrap($string,75,”<br>”);
Output
Malaysia negara maju, aman, makmur dan sentoasa Terdiri daripada
14 buah negeri dan sebuah kerajaan persekutuan
67
69. Pengaturcaraan PHP
Number (Random)
To get spcific number in random, we must put a value in the ().
Example :
<?php
$random_number = rand(0,10);
echo "$random_number";
?>
The output
0
Pengaturcaraan PHP
Password Encrypt – md5
To encrypt the password
Example :
<?php
$passwd = md5($password);
echo "$passwd";
?>
The output
ddf3rf5765g434dfg676
69