Variables Scope in PHP : Explained in easy language

Variables Scope in PHP

There are three types of variable scopes in PHP .  They are as follows:

1)      Local

2)      Global

3)      Static

Local Scope : When a variable declared inside a function (has a local scope ) and it can only be accessed within that function, the variable is called as local scope variable .

E.g.

<?php

function localvar()

{

$x=6; //local scope variable

echo "Variable x inside function is : $x";

}

localvar();

echo "Variable x outside function is : $x";//generate an error like undefined variable

?>

 

Output:  

Variable x inside function is : 6

Notice: Undefined variable: x

Variable x inside function is :

 

Global Scope : When a variable declared outside a function (has a global scope) and it can only be accessed outside a function, the variable is called as global scope variable .

E.g.

 <?php

$x=10; //global scope

function globalvar()

{

echo "Variable x inside function is : $x";//generate an error like undefined variable

}

globalvar();

echo "Variable x outside function is : $x";

?>

Output:

Notice: Undefined variable x

Variable x inside function is :

Variable x outside function is : 10

Global Keyword : By using global keyword we can access a global variable within a function. Just add or write global keyword before the variables inside the function. As follows,

e.g.

<?php

$x=10; //global scope

function globalvar()

{

            global $x;//By using global keyword

echo "Variable x inside function is : $x<br>";

}

globalvar();

echo "Variable x outside function is : $x";

?>

Output :

Variable x inside function is : 10

Variable x outside function is : 10

 

Static Scope : When a function is executed , all of its variables are deleted. However we want a local variable not to be deleted. We need it for further job. Use the static keyword when you first declared the variable . Then each time the function is called , the variable will still have the information it contained from the last time the function called.

e.g.

<?php

function scopevar (){

            static $x=11;

            echo $x;

            $x++;

}

scopevar ();

echo "<br>";

scopevar();

echo "<br>";

scopevar ();

?>

Output :

11

12

13

     

              In that way we learn variables scope in short .

Note: Read this blog regularly for important concepts and interview questions.

This blog is useful for IT students, IT freshers, BCA/MCA freshers. This blog contains Resume Tips, interview questions with answers.

PHP Interview questions with answers for Freshers - 1

Many interview questions we already listed on this blog, please read through out the posts related to PHP interview questions.


Q. What is the use of "echo" in php?
Answer: It is used to print a data in the webpage,
Example: <?php echo 'Welcome to Technology Park'; ?>
It will print the output or text on webpage as:
Welcome to Technology Park

Q. How to include a file to a php page?
VERY IMPORTANT INTERVIEW QUESTION
Answer: We can include a file using "include() " or "require()" function with file path as its parameter.

Q. How stop the execution of a php scrip ?
Answer: exit() function is used to stop the execution of a page.
At any point of script you can use the exit or exit() statement.

example:
<?php
echo "Welcome to Technology Park";
exit();
echo "not printed";
?>

Output:
Welcome to Technology Park

Q. How do you define a constant?
Answer:Using define() directive, like define ("MYCONSTANT",150)


Keep visiting the blog regularly for Latest Interview questions and Resume Tips.

PHP program to check whether the given number is palindrome or not

This PHP program is very useful for IT freshers.

Most of the IT companies ask this program in technical interview.




PHP program to check whether the given number is palindrome or not.

<?php
// PHP program to check whether the given number is palindrome or not
$n=123;
$rev=0;
$n1=$n;
while((int)$n > 0){
$rem = $n % 10;
$rev = ($rev*10) + $rem;
$n = (int)$n / 10;
}
echo "Reverse of $n1 = ".$rev."<br/>";
if($n1 == $rev){
echo "$n1 is palindrom number";
}else{
echo "$n1 is not palindrom number";
}
?>

This blog is very useful for IT Freshers.
Use right side menus to read useful posts like Resume Tips, Interview questions, Jobs, Programming, etc.

Other important Posts:
How to find PHP version through command prompt in windows? 

Important PHP string functions


PHP program to check whether the given number is prime or not

This post is very important for IT Students and IT freshers.

The most important program asked in various interviews or technical tests:
Write a PHP program to check whether the given number is prime or not.




What is Prime number: the number which is divisible by 1 and itself only.


So, here is the Program to check whether the given number is prime or not.

<?php
// What is Prime number: the number which is divisible by 1 and itself only.
$n=6; // The number which we want to check if it is PRIME or NOT PRIME
$prime=true;
for($i=2;$i<$n;$i++){
if($n%$i == 0){
$prime = false; // If Number is divisible by the $i iteration, it is not prime
break;
}
}
if($prime){
echo "PRIME";
}else{
echo "NOT PRIME";
}

?>

Output:
NOT PRIME

// when we assign value to n is 5 then output will be PRIME
--------------------------------------------------------------------------------------------




Other important posts for students of BCA/MCA/MCM/Msc/Bsc/MBA-IT/BE/BTech

Guidance for IT Students

Future of PHP Developer

PHP: Past, Today and Future

This blog is very helpful for IT Students and IT Freshers.


Database connection using PHP MySqli

For PHP freshers, one important thing is mysql_* functions are deprecated. Instead of mysql_* functions now we use mysqli_* functions.

PHP mysqli_connect() Function is used for connection to mysql database.




Example
Open a new connection to the MySQL server:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>


If we are using wamp or xamp on localhost,
my_user = root

my_password = "" (blank/empty)
my_db = your database name


This function returns an object representing the connection to the MySQL server, the returned connection object is used for executing mysql queries.


Insert Data Into MySQL Using MySQLi:
The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Example:
The following examples add a new record to the "MyGuests" table:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>


In this way, we just understood the concept and basics of mysqli connection.



Multidimensional Arrays in PHP: syntax and example

Multidimensional Arrays in PHP:
In previous post Arrays in PHP we learned Arrays and types of arrays.
We understood the concept of regular array that is indexed array, it is also called numeric array. We understood associative array.

Now we are going to understand Multidimensional array.
A multidimensional array is an array containing one or more arrays. It is also called array of array.

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Two-dimensional Arrays:
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).




example:
<?php
$students=array(
          array('Vanesh', 'MCA', '78'),
          array('Ganesh', 'MCM', '83'),
          array('Ramesh', 'MSC', '64'),
);

echo $students[0][0]." ".$students[0][1]." ".$students[0][2]. "<br/>";
echo $students[1][0]." ".$students[1][1]." ".$students[1][2]. "<br/>";
echo $students[2][0]." ".$students[2][1]." ".$students[2][2]. "<br/>";

?>


output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64

We can print this array using foreach loop as:

<?php
$students=array(
          array('Vanesh', 'MCA', '78'),
          array('Ganesh', 'MCM', '83'),
          array('Ramesh', 'MSC', '64'),
);
foreach($students as $key => $val){
  foreach($val as $v){
      echo $v." ";
    }
  echo "<br/>";
}
?>

output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64

Arrays in PHP

Arrays in PHP:
An array stores multiple values in one single variable.




An array is a data structure that stores one or more similar type of values in a single value.

Types of array:

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.

Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.

Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.

Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example
Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. In PHP, the array() function is used to create an array.

<?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>

Output:
Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five 

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.";
?>

OUTPUT:
Peter is 35 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>";
}
?>

OUTPUT:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43




Multidimensional Arrays:

Multidimensional Arrays will learn in next lession. 

For loop in PHP : Introduction with Example

The PHP for Loop:



The for loop is used when you know how many times you want to execute a statement or a block of statements.

Today we are going to learn for loop in php.

Syntax:

for (init counter; test counter; increment counter) {
    code to be executed;
}

Parameters:

init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example
<?php 
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";

?>

OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10