Sie sind auf Seite 1von 32

Working with strings in PHP:

String : A string is a sequence of characters, like "Hello world!”.

Php supports various string functions like:

1. strlen() --- function returns the length of a string.

<?php

echo strlen("Hello world!");

?>

2. str_word_count()----function counts the number of words in a string:

<?php

echo str_word_count("Hello world!");

?> 

2. strrev()---function reverses a string:

<?php
echo strrev("Hello world!");
?> 
The output of the code above will be: !dlrow olleH.

3. strpos()----function searches for a specific text within a string.

If a match is found, the function returns the character position of the first
match. If no match is found, it will return FALSE.
<?php
echo strpos("Hello world!", "world");
?> 
 
the output of the code above will be: 6.

Tip: The first character position in a string is 0 (not 1).


4. str_replace()---- function replaces some characters with some
other characters in a string.

<!DOCTYPE html>
<html>
<body>
<?php
echo str_replace("world", "Dolly", "Hello world!");
?> 
 
</body>
</html>

The output of the code above will be: Hello Dolly!

5.The stristr() function searches for the first occurrence of a string

inside another string. This function is case-insensitive. For a case-

sensitive search, use strstr()function.

<?php

echo stristr("Hello world!","WORLD");

?>

Output:World!

6.strstr():Finds the first occurrence of a string inside another string(case-

sensitive)

<?php

echo strstr("Hello world!","WORLD");

?>

No output
7.substr_count():The substr_count () function counts the number of

times a substring occurs in a string. The substring is case-sensitive.

<?php

echo substr_count("Hello world. The world is nice","world");

?>

Output:2

8.strtoupper():Converts a string to uppercase letters

<?php
echo strtoupper("HelloWORLD!");
?> 
 
Output:HELLO WORLD!

9.strtolower():Converts a string to lowercase letters

<?php
echo strtolower("HelloWORLD.");
?>
   Output:
hello world.

10: ucfirst():Converts the first character of a string to uppercase

<?php
echo ucfirst("helloworld!");
?> 
 Output:Hello world!

11. lcfirst():Converts the first character of a string to lowercase

<?php
echo lcfirst("Helloworld!");
?> 
 Output:hello world!
12. ucwords():Converts the first character of each word in a string to

uppercase

<?php

echo ucwords("helloworld");

?> 

Output:Hello World
Numeric functions:
1) Number_format:Used to formats a numeric
value using digit separators and decimal
points
<?php
echo
number_format(2509663);
?>
2) Rand():Used to generate a random number.
<?php
echo rand();
?>
3) round():Round off a number with decimal
points to the nearest whole number.
<?php
echo round(3.49);
?>
3
4) sqrt():Returns the square root of a number
<?php
echo sqrt(100);
?>
10
5) cos(): Returns the cosine
<?php
echo cos(45);
?>
0.52532198881773
6) sin():Returns the sine
<?php
echo sin(45);
?>
0.85090352453412
7) tan():Returns the tangent
<?php
echo tan(45);
?>
1.6197751905439
8) pi(): Constant that returns the value of PI
<?php
echo pi();
?>
9) abs() : Return the absolute value of different numbers:

<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
?>

10) floor()  Round numbers down to the nearest integer:

<?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
?>

11) pow() function returns x raised to the power of y.


<?php
echo(pow(2,4) . "<br>");
echo(pow(-2,4) . "<br>");
echo(pow(-2,-4) . "<br>");
echo(pow(-2,-3.2));
?>

12) The max() function returns the numerically maximum value.

<?php
  
echo (max(12, 4, 62, 97, 26));
  
?>

<?php
  
echo (max(array(28, 36, 87, 12)));
  
?>

13) The min() function returns the numerically minimum value.

<?php
  
echo (min(12, 4, 62, 97, 26));
  
?>

<?php
  
echo (min(array(28, 36, 87, 12)));
  
?>
What is an Array?

An array is a special variable, which can hold more than

one value at a time.

If you have a list of items (a list of car names, for example), storing the
cars in single variables could look like this:

$cars1 = "Volvo";

$cars2 = "BMW";

$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific
one? And what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access
the values by referring to an index number.

Create an Array in PHP

In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index


 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays

There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like
this:

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";

$cars[1] = "BMW";

$cars[2] = "Toyota";

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to
them.

There are two ways to create an associative array: 

$age = array("Peter"=>"35", "Ben"=>"37",

"Joe"=>"43");

or:

$age['Peter'] = "35";

$age['Ben'] = "37";

$age['Joe'] = "43";

The named keys can then be used in a script:

Example
<?php

$age

= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";

?>

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could
use a foreach loop, like this:

Example
<?php

$age

= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {

    echo "Key=" . $x . ", Value=" . $x_value;

    echo "<br>";

Array functions:

1. array_push() to insert an element into the array

<?php

$a=array("red","green");

array_push($a,"blue","yellow");

print_r($a);

?>

output: Counts all the values of an array


2.array_reverse:print the array elements in reverse

<?php

$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota";

print_r(array_reverse($a));

?>

output:

Array ( [c] => Toyota [b] => BMW [a] => Volvo )

3. The array_chunk() function splits an array into chunks of new


arrays.

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43","Harry"=>"50");
print_r(array_chunk($age,2,true));

?>

Output:

Array ( [0] => Array ( [Peter] => 35 [Ben] => 37 ) [1] => Array ( [Joe] => 43 [Harry] => 50 )

4 . array_combine Creates an array by using the elements from one "keys"


array and one "values" array

<?php

$fname=array("Peter","Ben","Joe");

$age=array("35","37","43");

$c=array_combine($fname,$age);

print_r($c);

?>

Output:Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )


2. array_count_values: Counts all the values of an array

<?php

$a=array("A","Cat","Dog","A","Dog");

print_r(array_count_values($a));

?>

3. Output:

Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )

6. array_diff :Compare arrays, and returns the differences (compare

values only)

<?php

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");

$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result= array_diff($a1,$a2);

print_r($result);

?>

Output:Array ( [d] => yellow )

7. array_fill_keys:

Fills an array with values, specifying keys

<?php

$keys=array("a","b","c","d");
$a1=array_fill_keys($keys,"blue");

print_r($a1);

?>

Output:

Array ( [a] => blue [b] => blue [c] => blue [d] => blue )

8. The array_slice() function returns selected parts of an array.

<?php

$a=array("red","green","blue","yellow","brown");

print_r(array_slice($a,2));

?>

output: Array ( [0] => blue [1] => yellow [2] => brown )

Start the slice from the third array element, and return the rest of the
elements in the array:

2nd example for array_slice function

<?php

$a=array("red","green","blue","yellow","brown");

print_r(array_slice($a,1,2));

?>

output: Array ( [0] => green [1] => blue )


9 array_splice() Function

Remove elements from an array and replace it with new elements:

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
array_splice($a1,0,2,$a2);
print_r($a1);
?>

output: Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )

10. extract function :

Imports variables into the current symbol table from an array

<?php

$a = "Original";

$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");

extract($my_array);

echo "\$a = $a; \$b = $b; \$c = $c";

?>

Output:

$a = Cat; $b = Dog; $c = Horse

11. Array_pad($array, $size, $value)- Returns an array with $value added to the end of

$array until it contains $size elements. If $size is negative, the value is added to the

start of the array.


Eg: <?php

$a=array("red","green");

print_r(array_pad($a,5,"blue"));

?>

Output : Array ( [0] => red [1] => green [2] => blue [3] => blue [4] => blue )

12 . array_merge($array1,$array2,....)- Returns an array with the elements of two or

more arrays in one array. String keys in $array2 overwrite string keys in $array1 but

numerical keys are appended.

Eg: <?php

$a1=array("red","green");

$a2=array("blue","yellow");

print_r(array_merge($a1,$a2));

?>

Output : Array ( [0] => red [1] => green [2] => blue [3] => yellow )

Eg: <?php

$a1=array("a"=>"red","b"=>"green");

$a2=array("c"=>"blue","b"=>"yellow");

print_r(array_merge($a1,$a2));

?>

Output : Array ( [a] => red [b] => yellow [c] => blue )
Eg : <?php

$a=array(3=>"red",4=>"green");

print_r(array_merge($a));

?>

Output : Array ( [0] => red [1] => green )

13.ARRAY STACK:

<?php

$numbers=array('a','b','c');

echo "The orginal array is :";

print_r($numbers);

array_push($numbers,50); //adds value to the end of the array

echo "<BR>The array after pushing 50 is : ";

print_r($numbers);

$x=array_pop($numbers); // Removes and returns the last value in array

echo "<BR> The number popped out is $x<BR>The array after the pop operation is :";

print_r($numbers);

?>

OUTPUT:

The orginal array is :Array ( [0] => a [1] => b [2] => c ) 

The array after pushing 50 is : Array ( [0] => a [1] => b [2] => c [3] => 50 ) 

The number popped out is 50

The array after the pop operation is :Array ( [0] => a [1] => b [2] => c )
14.ARRAY QUEUE:

<?php

$numbers=array('a','b','c');

echo "The orginal array is :";

print_r($numbers);

$x=array_shift($numbers); //Removes and returns the first value in an array

echo "<BR> The element removed using array_shift is : $x";

echo "<BR>The array after the array_shift operation is :";

print_r($numbers);

array_unshift($numbers,'z'); // adds value to the start of array

echo "<BR>The array after using array_unshift is :";

print_r($numbers);

?>

OUTPUT

The orginal array is :Array ( [0] => a [1] => b [2] => c ) 

The element removed using array_shift is : a

The array after the array_shift operation is :Array ( [0] => b [1] => c ) 

The array after using array_unshift is :Array ( [0] => z [1] => b [2] => c )
15.Get the sum and product of elements

<?php
$a=array(5,15,25);
echo array_sum($a);Returns sum of the elements in the array
?>

OUTPUT : 45

<?php
$a=array(5,5,2,10);
echo(array_product($a));//Returns the product of the elements in array
?>

OUTPUT : 500

16.Searching in arrays
The in_array() function searches an array for a specific value.

Syntax :in_array(search,array,type)

If the search parameter is a string and the type parameter is set to TRUE, the search is

case-sensitive.

<?php

$people = array("Peter", "Joe", "Glenn", "Cleveland");

if (in_array("Glenn", $people))

  {

  echo "Match found";

  }

else

  {

  echo "Match not found";


  }

?>

OUTPUT : Match found

The array_key_exists() function checks an array for a specified key, and returns true if

the key exists and false if the key does not exist.

array_key_exists(key,array)

<?php

$a=array("Volvo"=>"XC90","BMW"=>"X5");

if (array_key_exists("Volvo",$a))

  {

  echo "Key exists!";

  }

else

  {

  echo "Key does not exist!";

  }

?>

OUTPUT : Key exists!

Remember that if you skip the key when you specify an array, an integer key is

generated, starting at 0 and increases by 1 for each value.

<?php

$a=array("Volvo","BMW");

if (array_key_exists(0,$a))
  {

  echo "Key exists!";

  }

else

  {

  echo "Key does not exist!";

  }

?>

OUTPUT : Key exists!

The array_search() function search an array for a value and returns the key.

array_search(value,array,strict)

<?php

$a=array('a'=>123,'b'=>456,'c'=>789);

echo "Case insensitive search : " . array_search(789,$a);

echo "<BR>Case insensitive search : " . array_search('789',$a);

echo "<BR>Case sensitive search : " . array_search('789',$a,true);

?>

OUTPUT :

Case insensitive search : c

Case insensitive search : c

Case sensitive search :


The array_unique() function removes duplicate values from an array. If two or more array
values are the same, the first appearance will be kept and the other will be removed.

Syntax : array_unique(array,sorting_type)

<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>

OUTPUT :Array ( [a] => red [b] => green )

17.Sorting of Arrays
• Array sorting functions differs depending on

– Whether they sort in ascending or descending order

– Whether they preserve keys

– Whether they reindex the array

– Whether they sort by values or by keys

• All sorting function modify the original array

• Sorting functions uses three constants

– SORT_REGULAR- uses regular type casting rules of relational operators to sort

– SORT_STRING- cast each value to string before comparing

– SORT_NUMERIC-cast each value to number before comparing


The sort() function sorts an indexed array in ascending order and reindexes it.

Syntax : sort(array,sortingtype);

<?php

$cars=array("Volvo","BMW","Toyota");

$clength=count($cars);

echo "The original array is : <BR>";

for($x=0;$x<$clength;$x++)

echo $cars[$x];

echo "<br>";

sort($cars);

echo "The sorted array is : <BR>";

for($x=0;$x<$clength;$x++)

echo $cars[$x];

echo "<br>“; }

?>

OUTPUT:

The original array is : 


Volvo
BMW
Toyota
The sorted array is : 
BMW
Toyota
Volvo

The rsort() function sorts an indexed array in descending order and reindexes.

Syntax : rsort(array,sortingtype);
<?php

$numbers=array(4,6,2,22,11);

rsort($numbers);

$arrlength=count($numbers);

for($x=0;$x<$arrlength;$x++)

  {

  echo $numbers[$x];

  echo "<br>";

  }

?>

OUTPUT :

22

11

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.

PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep.

The dimension of an array indicates the number of indices you need


to select an element.
 For a two-dimensional array you need two indices to select an element
 For a three-dimensional array you need three indices to select an
element

<?php

$cars = array

  (

  array("Volvo",22,18),

  array("BMW",15,13),

  array("Saab",5,2),

  array("Land Rover",17,15)

  );

  echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0]

[2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1]

[2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2]

[2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3]

[2].".<br>";

?>

output:Volvo: In stock: 22, sold: 18.

BMW: In stock: 15, sold: 13.

Saab: In stock: 5, sold: 2.

Land Rover: In stock: 17, sold: 15.


PHP User Defined Functions

Besides the built-in PHP functions, we can create our own functions. A function is a block of
statements that can be used repeatedly in a program. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a
value. There are two parts which should be clear to you −

 Creating a PHP Function


 Calling a PHP Function
A function will not execute immediately when a page loads. A function will be executed by a
call to the function.

Create a User Defined Function in PHP:


A user defined function declaration starts with the keyword "function":

Syntax:
function functionName() {
    code to be executed;
}

Note: A function name can start with a letter or underscore (not a number). Function names
are NOT case-sensitive.
The opening curly brace ( { ) indicates the beginning of the function code and the closing
curly brace ( } ) indicates the end of the function.

Example:
<html>
<head>
<title>Writing PHP Function</title>
</head>

<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}

/* Calling a PHP Function */


writeMessage();
?>
Output: You are really a nice person, Have a nice time!

PHP Function Arguments/Parameters:


Information can be passed to functions through arguments. An argument is just like a
variable inside your function. Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just separate them with a
comma.

Following example takes two integer parameters and add them together and then print
them.

Example:
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>
<?php
function addFunction($num1, $num2) //function
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20); // fun call
?>
</body>
</html>
Output:

Sum of the two numbers is : 30

Example

The following example has a function with two arguments ($fname and $year):

<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year)
{
    echo "$fname . Born in $year <br>";
}

familyName("Hege","1975");
familyName("Stale","1978");
familyName(“Jim","1983");
?>

</body>
</html>

Output:

Hege . Born in 1975 


Stale. Born in 1978 
Kai Jim . Born in 1983

PHP Functions - Returning values


A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from a
function.

Example:

<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>

</body>
</html>
Output:

Returned value from the function : 30

Example

<!DOCTYPE html>
<html>
<body>

<?php
function sum($x, $y) {
    $z = $x + $y;
    return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";


echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

</body>
</html>

Output:

5 + 10 = 15
7 + 13 = 20
2+4=6

Passing Arguments by Reference


It is possible to pass arguments to functions by reference. This means that a reference to
the variable is manipulated by the function rather than a copy of the variable's value.

Any changes made to an argument in these cases will change the value of the original
variable. You can pass an argument by reference by adding an ampersand to the variable
name in either the function call or the function definition.
Following example depicts both the cases.

Example:

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

function array_fns($array, &$sum, &$prod, &$avg){ //Return multiple values


$sum=array_sum($array);
$prod=array_product($array);
$avg=$sum / count($array);
}

$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";

$list = array(1,4,6,8);
array_fns($list, $s, $p, $a);
echo "Sum = $s, Product = $p, Average = $a";
?>
</body>
</html>

Output:
Original Value is 10
Original Value is 16
Sum = 19, Product = 192, Average = 4.75
PHP Default Argument Value:
You can set a parameter to have a default value if the function's caller doesn't pass it.

Example
<!DOCTYPE html>
<html>
<body>

<?php
function setHeight($minheight = 50) {
    echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>

</body>
</html>

Output:
The height is : 350 
The height is : 50 
The height is : 135 
The height is : 80

PHP - File Inclusion


You can include the content of a PHP file into another PHP file before the server executes it.
There are two PHP functions which can be used to included one PHP file into another PHP
file.
The include() Function
The require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements
that can be reused on multiple pages. This will help developers to make it easy to change
the layout of complete website with minimal effort. If there is any change required then
instead of changing thousand of files just change included file.
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the include() function
generates a warning but the script will continue execution.
Assume you want to create a common menu for your website. Then create a file menu.php
with the following content.

<a href="http://www.tutorialspoint.com/index.htm">Home</a> -
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a> <br />

Now create as many pages as you like and include this file to create header. For example
now your test.php file can have following content.
<html>
<body>

<?php include("menu.php"); ?>


<p>This is an example to show how to include PHP file!</p>

</body>
</html>

Example #1 Basic include example

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php
echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple
?>
The require() Function
The require() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the require() function
generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not
continue executing if files are missing or misnamed.

<html>
<body>

<?php require ("xxmenu.php"); ?>


<p>This is an example to show how to include wrong PHP file!</p>

</body>
</html>

Das könnte Ihnen auch gefallen