How to reverse the order of an array in PHP

We can reverse the order of the values in an array using the array_reverse() function. This is a built-in PHP function that takes an array as its input and returns a new array having the reverse ordered elements.

This function arranges all the elements of an array in just the opposite order of the given array.

Syntax
array_reverse(array, preserve

Parameter Values

array - Required. Specifies an array
preserve - Optional. Specifies if the function should preserve the keys of the array or not. Possible values:
                true
                false


Example

<?php

 
      $array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
      $new_array = array_reverse($array);
      print_r($new_array);

?>

Output

Array ( [0] => jQuery [1] => PHP [2] => JavaScript [3] => CSS [4] => HTML )

Using for loop

We can also reverse the order of the values of the input array using for loop. We just have to specify some conditions within the for loop and then print the values of an array using echo.
Example: Reverse the values of an array using for loop

In the given example, we have reversed the values of the given array name $array using the for loop.

<?php
      $array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
      $size = sizeof($array);

      for($i=$size-1; $i>=0; $i--){
          echo $array[$i];
          echo "<br>";
      }
   

?>

Output

jQuery
PHP
JavaScript
CSS
HTML

How to check if a key exists in an array in PHP

You can use the PHP array_key_exists() function to test whether a given key or index exists in an array or not. This function returns TRUE on success or FALSE on failure.

Syntax
array_key_exists(key, array

Parameter Values

key - Required. Specifies the key

array - Required. Specifies an array

<?php
$cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York");
 
// Testing the key exists in the array or not
if(array_key_exists("France", $cities)){
    echo "The key 'France' is exists in the cities array";
}
?>

Output

The key 'France' is exists in the cities array

How to check if a value exists in an array in PHP

You can use the PHP in_array() function to test whether a value exists in an array or not.

The in_array() function searches an array for a specific value.

Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
Syntax
in_array(search, array, type

Parameter Values

search:     Required. Specifies the what to search for
array:       Required. Specifies the array to search
type:        Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array. 

Let's take a look at an example to understand how it basically works

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of Testing Whether a Value Exists in PHP Array</title>
</head>
<body>

<?php
$zoo = array("Lion", "Elephant", "Tiger", "Zebra", "Rhino", "Bear");
if(in_array("Elephant", $zoo)){
    echo "The elephant was found in the zoo.";
}
echo "<br>";
if(in_array("Tiger", $zoo)){
    echo "The tiger was found in the zoo.";
}
?>

</body>
</html>

Output 

The elephant was found in the zoo.
The tiger was found in the zoo.

How to remove duplicate values from an array in PHP

You can use the PHP array_unique() function to remove the duplicate elements or values form an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys.

array_unique($array, $flags);

The array_unique() function has two parameters. The details of its parameters are as follows.

$array -   It is the array from which we want to remove the duplicate values. 

$flags  -    It specifies the sorting pattern for the array. The sorting flags are of five types. SORT_REGULAR compares items normally
SORT_NUMERIC compares items numerically
SORT_STRING compares items as strings
SORT_LOCALE_STRING compares items as strings, based on the current locale.

Example

<?php
$array = array("a" => "moon", "star", "b" => "moon", "star", "sky");
 
// Deleting the duplicate items
$result = array_unique($array);
print_r($result);
?>

Output

Array ( [a] => moon [0] => star [2] => sky ) 


Example

<?php
$array = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy","Daffodil","Daisy","Lili","Jasmine","Jasmine");
echo("Array before removal: \n");
var_dump($array);
$array = array_unique($array, SORT_NUMERIC);
echo("Array after removal: \n");
var_dump($array);
?>

Output

Array before removal:
array(11) {
  [0]=>
  string(4) "Rose"
  [1]=>
  string(4) "Lili"
  [2]=>
  string(7) "Jasmine"
  [3]=>
  string(8) "Hibiscus"
  [4]=>
  string(8) "Daffodil"
  [5]=>
  string(5) "Daisy"
  [6]=>
  string(8) "Daffodil"
  [7]=>
  string(5) "Daisy"
  [8]=>
  string(4) "Lili"
  [9]=>
  string(7) "Jasmine"
  [10]=>
  string(7) "Jasmine"
}
Array after removal:
array(1) {
  [0]=>
  string(4) "Rose"
}


The function has now sorted the array numerically.

PHP program to merge two arrays into a new array

You can use the PHP array_merge() function to merge the elements or values of two or more arrays together into a single array. The merging is occurring in such a way that the values of one array are appended to the end of the previous array. Let's check out an example.

array_merge() Definition and Usage

The array_merge() function merges one or more arrays into one array.

Tip: You can assign one array to the function, or as many as you like.

Note: If two or more array elements have the same key, the last one overrides the others.

Note: If you assign only one array to the array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value (See example below).

<?php
$arr1 = array("Delhi","Lucknow");
$arr2 = array("Mumbai","Noida");
print_r(array_merge($arr1,$arr2));
?> 

Output

Array ( [0] => Delhi[1] => Lucknow[2] => Mumbai[3] => Noida)

Example for Merge two associative arrays into one array

<?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 )  

PHP Recursive Functions

 PHP supports recursion, or in simple words, we can call a PHP function within another function without any argument, just like in C++. 200 is considered to be the maximum recursion level to avoid any crash of code.

Lets take a look at a simple example of a recursive function in PHP 

<?php

//Our recursive function.

function recursive($num){
    //Print out the number.
    echo $num, '<br>';
    //If the number is less or equal to 50.
    if($num < 50){
        //Call the function again. Increment number by one.
        return recursive($num + 1);
    }
}

//Set our start number to 1.
$startNum = 1;

//Call our recursive function.
recursive($startNum);

?>

The code above is pretty simple. Basically, the function checks to see if the number is less than 50. If the number is less than 50, then we increment the number and call the function again. This process is repeated until the number has reached 50.

Note that if you need to go deeper than 100 levels, then you will need to increase the xdebug.max_nesting_level setting. You can do this via the ini_set function if you’re on a hosted platform that allows you to modify PHP ini settings on the fly:

<?php

ini_set('xdebug.max_nesting_level', 150);

?>

Example 2: Code to generate factorial of a number using recursive function in PHP.

<!DOCTYPE html>
<html>
<body>
 
<?php    
function factorial($n)    {    
if ($n < 0)    
return -1;  
if ($n == 0)    
return 1;
return ($n * factorial ($n -1));    
}    
 
echo factorial(10);    
?>    
 
</body>
</html> 

Out put : 3628800 

MySql Interview questions and answers for freshers

MySQL

MySQL is a relational database management system (RDBMS) developed by Oracle that is based on structured query language (SQL).

A database is a structured collection of data. It may be anything from a simple shopping list to a picture gallery or a place to hold the vast amounts of information in a corporate network. In particular, a relational database is a digital store collecting data and organizing it according to the relational model. In this model, tables consist of rows and columns, and relationships between data elements all follow a strict logical structure. An RDBMS is simply the set of software tools used to actually implement, manage, and query such a database.

What is difference between DBMS and RDBMS

DBMS and RDBMS both are used to store information in physical database but there are some remarkable differences between them.

DBMS

DBMS applications store data as file.

In DBMS, data is generally stored in either a hierarchical form or a navigational form.

Normalization is not present in DBMS.

DBMS does not apply any security with regards to data manipulation.

DBMS uses file system to store data, so there will be no relation between the tables.

DBMS has to provide some uniform methods to access the stored information.

DBMS does not support distributed database.

DBMS is meant to be for small organization and deal with small data. it supports single user.

Examples of DBMS are file systems, xml etc.

RDBMS

RDBMS applications store data in a tabular form. 

In RDBMS, the tables have an identifier called primary key and the data values are stored in the form of tables.

Normalization is present in RDBMS.

RDBMS defines the integrity constraint for the purpose of ACID (Atomocity, Consistency, Isolation and Durability) property.

in RDBMS, data values are stored in the form of tables, so a relationship between these data values will be stored in the form of a table as well.

RDBMS system supports a tabular structure of the data and a relationship between them to access the stored information.

RDBMS supports distributed database.

RDBMS is designed to handle large amount of data. it supports multiple users.

Example of RDBMS are mysql, postgre, sql server, oracle etc.

How to make database connection to mysqli in php

<?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();
  }
?>

How to make database connection to PHP Data Object in php 

<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','my_user');
define('DB_PASS','my_password');
define('DB_NAME','my_db');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>

What is join in SQL

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:
 

(INNER) JOIN: Returns records that have matching values in both tables    

LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table.

RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table.

FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table.

What is difference between ORDER BY and GROUP BY in SQL

ORDER BY  used to sort the result in ascending or descending order. By default records are sort in ascending
Eg- SELECT column1, column2, …FROM tablename ORDER BY column1… ASC|DESC;
GROUP BY used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
Eg- SELECT columnname FROM tablename WHERE condition GROUP BY columnname

What is difference between FLOAT and DOUBLE

FLOAT and DOUBLE both represents approximate numerical data values. MySql uses four bytes for single precision values and eight bytes for double precision values .
A Float is for single-precision value wheres DOUBLE is for double precision values and DOUBLE allows greater accurcy than FLOAT.
Float saves floating point numbers upto eight places and DOUBLE saves floating point numbers upto 18 places.

How to find second maximum salary

SELECT max(salary) FROM tblname WHERE  salary <( SELECT max(salary) FROM tblname )

What is difference between TRUNCATE and DELETE in mysql

1: DELETE  is a DML(data manipulation language) command whereas truncate is a DDL(data definition language) command.
2 : Truncate is much faster than Delete.
3 : We can not roll back in truncate but in delete we can rollback.
4 : We can not use where clause in truncate but in delete we can use conditions using where clause

What is difference between PRIMARY key and UNIQUE Key in sql

1: UNIQUE key can be a NULL value but PRIMARY key can not  take NULL values.
2:A table can have multiple UNIQUE key but  can only one PRIMARY key.
How to concatenate two fields in MySql
In MySQL CONCAT function is used to concatenate two strings to form a single string
Synatx : SELECT CONCAT(column1,column2)  FROM tblname.
Ex          : SELECT CONCAT(first_name,last_name) FROM employee

What is difference between mysql_connect and mysql_pconnect

1: While using the mysql_pconnect  the function would try to find a connection that is already open with   same host,username and password ie.(persistant connection) .If connection found an identifier will be returned instead of opening new connection. And with mysql_connect a  new connection is always established .
2:While using mysql_pconnect the connection will not closed after the execution of script for future use and in mysql_connect the connection will automatically close when execution of script ends.
3 :mysql_pconnect uses less resources than mysql_connect.

What is difference between CHAR and VARCHAR data types in sql

CHAR  used to store  fixed length memory storage whereas VARCHAR is used for variable length memory storage .In VARCHAR if we used less space than defined space ,then the remaining space is not wasted , but In CHAR if we use less space than defined space then remaining space is wasted.
CHAR stores only character values  whereas VARCHAR stores alphanumeric values
 

What is difference between MyISAM and InnoDB storage engines in mysql

1 : InnoDB provides us row level locking while MyISAM provides us table level locking.
2 : InnoDB offers foreign key constraints wheres in MyISAM does not have foreign key constraints.
3 : InnoDB does not have full text search wheres MyISAM provides us full text search.
 

How to get current date in MySql

SELECT CURRENT_DATE();


What type of storage engine mysql support

Below are some storage engines names that a mysql support.
1 : MyISAM.
2 :InnoDB
3 :Memory
4 :CSV
5 :Merge etc.


How to find unique records in MYSQL

SELECT DISTINCT columnname FROM tablename;

How to fetch records sorted in an ascending (asc) or descending (desc)

SELECT col1,col2 FROM tablename ORDER BY col2 DESC;
ELECT col1,col2 FROM tablename ORDER BY col2 ASC;
How to get total number of rows

SELECT COUNT(*) FROM tablename;
How to Delete a column from a table

alter table [table name] drop column
;

How to add a column from a table

alter table [table name] add column [new column name] varchar (20);


How do you return the a hundred items starting from 10th position

SELECT item_name FROM items LIMIT 10, 100.


What is the difference between primary key and candidate key


Every row of a table is identified uniquely by primary key. There is only one primary key for a table.
Primary Key is also a candidate key. By common convention, candidate key can be designated as primary and which can be used for any foreign key references.


Which MySQL Datatype should be used for storing boolean values

For MySQL 5.0.3 and higher, you can use BIT.
For versions lower than 5.0.3 you can use bool and boolean which are at the moment aliases of tinyint(1).


What is the different between NOW() and CURRENT_DATE()


NOW () is used to show current year,month,date, hours,minutes and seconds.
CURRENT_DATE() shows current year,month and date only.


What is command to check table is exist


CHECK TABLE table_name;


Write an SQL query to find names of employee start with ‘A’


SELECT * FROM Employees WHERE EmpName like ‘A%’ ;


What is heap table in MySQL

Tables that are present in memory is known as HEAP tables. When you create a heap table in MySQL,you should need to specify the TYPE as HEAP. These tables are commonly known as memory tables. They are used for high speed storage on temporary basis. They don’t allow BLOB or TEXT fields.


How to reset the MySQL root password

 To reset the root password for MySQL, follow the below steps;

1 :  Log in to your account using SSH.

2 : Stop the MySQL server using the appropriate command for your Linux distribution.

Command for CentOS and Fedora, type

service mysqld stop

Command for Debian and Ubuntu, type

service mysql stop

3: Restart the MySQL server with the —skip-grant-tables option. To do this, type the following command.

mysqld_safe --skip-grant-tables &

4: Log into MySQL using the following command.

mysql

5: At the mysql> prompt, reset the password. To do this, type the following command, replacing new-password with the new root password.

UPDATE mysql.user SET Password=PASSWORD('new-password') WHERE User='root';

6: At the mysql> prompt, type the following commands.

FLUSH PRIVILEGES;

exit;

7: Stop the MySQL server using the following command. You will be prompted to enter the new MySQL root password before the MySQL server shuts down.

mysqladmin -u root -p shutdown

8: Start the MySQL server normally. To do this, type the appropriate command for your Linux distribution.

For CentOS and Fedora, type

service mysqld start

For Debian and Ubuntu, type

service mysql start


How To Import and Export Database using the command line in MySQL

Importing and exporting databases is a common task in software development. You can use data dumps to back up and restore your information. You can also use them to migrate data to a new server or development environment.

Step 1 — Exporting a MySQL or MariaDB Database

The mysqldump console utility exports databases to SQL text files. This makes it easier to transfer and move databases. You will need your database’s name and credentials for an account whose privileges allow at least full read-only access to the database.

Use mysqldump to export your database:

mysqldump -u username -p database_name > data-dump.sql

    username  is the username you can log in to the database with
    database_name  is the name of the database to export
    data-dump.sql  is the file in the current directory that stores the output.

 

Step 2 — Importing a MySQL or MariaDB Database

To import an existing dump file into MySQL or MariaDB, you will have to create a new database. This database will hold the imported data.
 

mysql -u username -p new_database < data-dump.sql
 

 
    username is the username you can log in to the database with
    newdatabase is the name of the freshly created database
    data-dump.sql is the data dump file to be imported, located in the current directory


How to send mail from localhost XAMPP using PHP

 You can send mail from localhost with sendmail package , sendmail package is inbuild in XAMPP. So if you are using XAMPP then you can easily send mail from localhost.

 To send mail from localhost XAMPP using Gmail, configure XAMPP after installing it. Follow the below steps for the same.

Steps to Send Mail From Localhost XAMPP Using Gmail:

Open XAMPP Installation Directory.

Go to C:\xampp\php and open the php.ini file.


Find [mail function] by pressing ctrl + f.
Search and pass the following values:
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = YourGmailId@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t" 


Now, go to C:\xampp\sendmail and open the sendmail.ini file.

Find [sendmail] by pressing ctrl + f.
Search and pass the following values
smtp_server=smtp.gmail.com
smtp_port=587 or 25 //use any of them
error_logfile=error.log
debug_logfile=debug.log
auth_username=YourGmailId@gmail.com
auth_password=Your-Gmail-Password
force_sender=YourGmailId@gmail.com(optional) 

Here is the actual code that you have to write

Script To Send Mail:

<?php
$to_email = "receipient@gmail.com";
$subject = "Simple Email Test via PHP";
$body = "Hi, This is test email send by PHP Script";
$headers = "From: sender email";

if (mail($to_email, $subject, $body, $headers)) {
    echo "Email successfully sent to $to_email...";
} else {
    echo "Email sending failed...";
}

?>

Note: If you are getting a warning message then Please configure “Less secure apps” settings as shown below. Sometimes without turning on the 'less secure apps' is the main reason the user didn't receive the mail.

Turning on 'less secure apps' settings as mailbox user

Go to your (Google Account).
On the left navigation panel, click Security.
On the bottom of the page, in the Less secure app access panel, click Turn on access.
If you don't see this setting, your administrator might have turned off less secure app account access (check the instruction above).
Click the Save button.

 

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...