Pertemuan 2
Pertemuan 2
Pertemuan 2
Variables in PHP
A variable are used for storing a values, like text strings, numbers or arrays.
When a variable is set it can be used over and over again in your script
$var_name = value;
New PHP programmers often forget the $ sign at the beginning of the variable. In that case it will not
work.
<?php
$txt = "Hello World!";
$number = 16;
?>
In the example above, you see that you do not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on how they are set.
In a strongly typed programming language, you have to declare (define) the type and name of the
variable before using it.
String variables are used for values that contains character strings.
In this tutorial we are going to look at some of the most common functions and operators used to
manipulate strings in PHP.
After we create a string we can manipulate it. A string can be used directly in a function or it can be
stored in a variable.
Below, the PHP script assigns the string "Hello World" to a string
variable called $txt:
<?php
$txt="Hello World";
echo $txt;
?>
Hello World
Now, lets try to use some different functions and operators to manipulate our string.
The concatenation operator (.) is used to put two string values together.
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
<?php
echo strlen("Hello world!");
?>
12
The length of a string is often used in loops or other functions, when it is important to know when
the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no match is
found, it will return FALSE.
<?php
echo strpos("Hello world!","world");
?>
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and
not 7, is that the first position in the string is 0, and not 1.
For a complete reference of all string functions, go to our complete PHP String Reference.
The reference contains a brief description and examples of use for each function!
PHP Operators
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators