Translate

Monday, May 5, 2014

2. Variables in PHP

We create Variable ( variable ) to store values ​​temporarily when a program is operating . Variables that we can load value , such as String, Number, Array .
Creating Variable
Creating Variable in PHP must abide by the following principles :
. Start by $
. Variable names can (az, AZ, 0-9, and _)
Note : Variable names can not begin with numbers .
Here is a method of creating Variable in PHP

<?php
  $var_name = value;
?>
Example: Declaring variables in PHP
<?php
  $txt = 'Hello World';     // String
  $str = "itkonkhmer";     // String
  $x=16;                    // Integer
  $y = 15.10;              // Double
?>
Note: Variable data in PHP is based on the value we give it.

Type Casting

- Cast to String: Convert Variable to String
<?php
  $x= 6;            // Integer
  (string) $x;          // $x is String
?>
- Cast to Integer: Convert Variable to Integer

1
2
3
4
5
6
7
<?php
  $str = '6'// String
 (integer) $str// $str now is Integer
 // or (int) $str;
 $x = 10.50;  // Double
 (integer) $x;   //$x now is Integer
?>
- Cast to Float: Convert Variable to Double

1
2
3
4
<?php
  $x = 6;           // Integer
  (float) $x;           // $x now is float
?>
- Cast to Boolean: Convert Variable to Boolean

1
2
3
4
5
6
7
8
<?php
  $x = 1;
  $y = 0;      
  $bool1 = (bool) $x;
  $bool2 = (bool) $y;
  var_dump($bool1);
  var_dump($bool2);
?>
results

1
2
bool(true)
bool(false)

Settype()

Settpype () Function used to Convert Variables.
Syntax:
?
1
2
3
<?php
   Settype($var_name,stringdatatype);
?>
example
?
1
2
3
4
<?php
  $x = 20.25;<br>  settype($x,"integer");
  echo $x;<br>  // result : 20
?>

Gettype()

Gettype () Function Return String data type Variable.
?
1
2
3
4
<?php
  $x = 20.25;<br>  echo gettype($x) . "<br/>";
  $str = "Hello";<br>  echo gettype($str);
?>
Result
?
1
2
double
string

Var_dump()

var_dump () Function to return the String Data type and value of the variable.
<?php
  $x = 20.25;<br>  $str = "Hello";
  $bool = true;<br>  echo var_dump($x) . "<br/>";
  echo var_dump($str) . "<br/>";
  eho var_dump($bool);
?>
Result

float(20.25)
string(5) "Hello"
bool(true)

0 comments:

Post a Comment