Tag Archives: learn php online

PHP convert string to number


PHP convert string to number : We sometimes need to convert the string to integer. There are many ways to convert string to number. Here in this tutorial we are going to explain how you can convert a string to number forcefully using different methods. We will also explain how to convert string to float etc.


PHP convert string to number – Interger Example

If you have string like – “33.3” and you want to convert it to integer use the type cast as below –

PHP convert string to number – integer example:

$number = "33.3";
$int = (int)$number;

In this example $number variable contains the string with “33.3”. Double quotes makes it string so we have used type cast int to convert it to integer.


More About String to Number

Let us learn more about conversion –


PHP convert string to Integer : inval() function Example-

You can also convert string to integer using the function intval. Here is an example of intval-

PHP convert string to integer example:

$number = "33.3";
$int = intval($number);

The above function takes the string and returns the integer.

Now let us have some example about the float conversion.

PHP convert string to float Method 1

You can also convert string to float using the type cast (double) as below –

PHP convert string to float example:

$number = "33.3";
$int = (double)$number; // will give 33.3
or 
$int = (float)$number; // will give 33.3

The double type cast will convert the number in float.

PHP convert string to float Method 2 : floatval() Function Example

You can also convert string to float using the floatval() function as below –

PHP convert string to float example:

$number = "33.3";
$int = floatval($number); // will give 33.3

The floatval() takes string and converts it to the float as above.

PHP Set HTTP header to UTF-8


PHP Set HTTP header to UTF-8: Sometimes we need to set the HTTp header to UTF-8 in php. header() is used to set the HTTp header to UTF-8. The header() sends a raw HTTP header. In this tutorial we are going to explain how you can set the HTTP header to UTF-8 using PHP.


PHP Set HTTP header to UTF-8

Use the header() function and add the charset utf-8 as below –

PHP Set HTTP header to UTF-8:

header('Content-Type: text/html; charset=utf-8');

Now call this before sending any output to the client. Add this at the starting of the page. There should be no blank space before it because it may cause error. You can check the headers already sent or not using the function headers_sent(). For the function headers_sent() you can refer – http://php.net/manual/en/function.headers-sent.php

Refresh page using PHP


Refresh page using PHP Function : Sometimes in php we need to reaload ie. refresh a page. There can be several ways to refresh a page in php we are going to explain few of them. In this tutorial we will explain how you can refresh a page after some interval of time.


Refresh page using PHP

You can use the header() function to refresh the page here is an example to refresh the page using this function-

Refresh page using PHP function:

$second = 10;
header("Refresh:$second");

This will refresh page after each 10 seconds.

Refresh page using PHP And Redirect to another page-

If you to redirect to another page after refreshing the page you can add the second parameter ie. page you want to redirect-

Refresh page using PHP And Redirect to another page-:

$second = 10;
header("Refresh:$second; url=testpage.php" );

This will refresh the page after the given time and redirect to the given page.

More About PHP Refresh Page

Let us have look over another methods which we can use to refresh the page in php.

Refresh page in PHP using HTML META

You can also refresh a page using the HTML META as below-

Refresh page in PHP using HTML META Example

echo("");

Refresh page in PHP using Javascript

You can also refresh a page using the javascript as below-

Refresh page in PHP using Javascript Example




You can also use the javascript to refresh the page in php. The above example will reload the same page after refreshing.

Php export data from mysql to excel


Php export data from mysql to excel : We sometimes need a script in php which can export the mysql table’s data into csv, excel or in some other format. Here in this tutorial we are going to create a script which will export the table’s data into excel file. In this tutorial we will go step by step with example and demo. You can download the complete script free.


Php export data from mysql to excel

Here are steps to export data from mysql to excel using PHP Script.

Table

First specify the table from which you want to export data in excel. Here we have created a script to create table in mysql. First of all please run the below script to create the table and insert the sample data so that we can proceed for php code which will pull data from this table and export it into the excel file.

Create My-Sql Table:

CREATE TABLE IF NOT EXISTS `test_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `phone` varchar(15) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8;

--
-- Dumping data for table `test_user`
--

INSERT INTO `test_user` (`id`, `name`, `email`, `phone`) VALUES
(1, 'John', 'johnk@yopemail.com', '121323232'),
(2, 'Kelly', 'kellyk@yopemail.com', '121212122'),
(3, 'Ryan', 'ryank@yopemail.com', '22222212'),
(4, 'Kojo', 'kojao@yopemail.com', '12144444'),
(5, 'Kinjal', 'kinjal@yopemail.com', '22555212'),
(6, 'Jonny', 'jonny@yopemail.com', '121334444'),
(7, 'Barak', 'barak@yopemail.com', '2444444512'),
(8, 'Uman', 'uman@yopemail.com', '12334444');

After running the above query in mysql you will have a table named test_user with above sample data.

Export data in excel from mysql using php

Php Script To Export Data from Mysql Table to Excel File

Here we have created simple script to export data from mysql table to excel file-

Php Script To Export Data from Mysql Table to Excel File & Download:



		';
		$no++;
	}
	?>
NO. NAME EMAIL PHONE
'.$no.' '.$data['name'].' '.$data['email'].' '.$data['phone'].'

Try it & Download »

Headers header(“Content-type: application/vnd-ms-excel”); & header(“Content-Disposition: attachment; filename=”.$fileName.”.xls”); are used to download convert the plain data in excel format and save it.

You can try and download the full code from the above link provided along with the try it button.

PHP script to detect mobile devices


PHP script to detect mobile devices : You can detect the mobile devices using the php script. Here is an example of getting mobile devices which uses user agent and pattern to match the mobile device.


PHP script to detect mobile devices

Php function to get mobile devices –

PHP script to detect mobile devices

function isMobileDevice() {
$match = preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
	return $match;
}

The function will return true if mobile device found else it will return false.

Warning: Invalid argument supplied for foreach() in Php


Warning: Invalid argument supplied for foreach() in Php: This warning comes when you are not passing array to foreach. To fix this warning you can use is_array to check the argument type supplied to foreach. Here is an example – How to fix Warning: Invalid argument supplied for foreach().


Warning: Invalid argument supplied for foreach() in Php

Add the is_array() method to fix the warning –

Warning: Invalid argument supplied for foreach()

$array = array("John", "Rimmy", "Kelly");
//now add the following check 
if(is_array($array)){
foreach($array as $data){
echo $data;
}

}

The above check will fix your problem.

PHP Check that variable is an array


PHP Check that variable is an array : PHP function is_array is used to check a variable whether it is array or not. it accepts one parameter as variable and finds it is array or not. Returns true if the variable is array else it returns false. Here we are going to explain this function with example –


PHP Check that variable is an array

Here is an example of how to check a variable is array or not –

PHP Check that variable is an array Example 1

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

if(is_array($array)){
echo "This is array.";
}else{
echo "This is not array.";
}
//will print - This is array

The above example will print – This is array because we passed array variable to check.

Now lets go with another example which is not array

PHP Check that variable is an array Example 1

$str = "abcd";

if(is_array($str)){
echo "This is array.";
}else{
echo "This is not array.";
}
//will print - This is not array

The above example will print – This is not array because we passed string variable to check and this function will refurn false so it will go in else condition.

PHP str_pad function


PHP str_pad function : Is used to pad a string to new length with another string. This function basically pads the string to the left, right or both side of the string with a string. It accepts the string as input parameter and returns the padded string with new length. We are going to explain the str_pad function with example and demo.


PHP str_pad function Syntax

The Syntax for the str_pad is given below-

PHP str_pad function Syntax

str_pad(string,length,pad_str,pad_type);

Parameters

The Input parameters are –

  • string : String to be padded
  • length : New length of string. It should be more than the original length of the string.
  • pad_str : It’s optional. This is string to be added as pad. If you do not add this option by default whitespace will be added.
  • pad_type :It’s optional. This decides which side to add pad – Left, Right or Both Side. Available options are –

    • STR_PAD_BOTH : Add pad to both sides.


    • STR_PAD_LEFT : Add pad to left side.


    • STR_PAD_RIGHT : Add pad to right side.

Output

Returns the padded string.

Technical Requirements

Technical requirements are –

PHP Version : 4.01

PHP str_pad function Example

Here is very basic example of str_pad function-

PHP str_pad function Example:

$string = "Welcome to Tutorialsplane.";
$paddedString = str_pad($string,30,'*',STR_PAD_RIGHT);
echo $paddedString;

Try it »

If you run the above example it will produce output like this –

PHP str_pad function Example

PHP number_format Function


PHP number_format Function : This function is used to format a number with grouped thousand. This function accepts one, two or four parameter not three. This function is important when you are working with the numbers. For example if you are working with price and you want to format numbers up to two digits of decimal, you can use number_format() function. Suppose you have a variable $price = “98”; if you use the function echo $formattedPrice = format_number($price,2); it will print 98.00.
We are going to describe this function with example and demo.


PHP number_format Function Syntax

Here is syntax of number_format Function

PHP number_format Function Syntax

number_format(number,decimals,dec_point,separator)

Parameters

  • number : The number you want to format. If other parameters are not set it will number with no decimal points and use thousand separator comma(,).
  • decimals : Used to set decimal points. Number will be formatted with decimal points.
  • dec_point : Separator for decimal point.
  • separator : Specifies the string for thousand separator.

Return Value

Returns the formatted number on the basis of the input parameters.

Technical Requirements

Php Version : 4+

PHP number_format Function Example 1

Here is very basic example with single parameter ie. number. PHP format number with commas is most common question here is the example of format number with comma –

PHP format number with commas

$number = "55789.99";
$formattedNumber = number_format($number);
echo $formattedNumber ;

Try it »

When you run the above example will produce the following output-

PHP number_format Function

PHP number_format Function Example 2

Here is example with single two parameters ie. number and decimal. PHP format number to 2 decimal places is also most common used example. Here is the example of format number with decimal –

PHP format number to 2 decimal places

$number = "55789.99";
$formattedNumber = number_format($number,2);
echo $formattedNumber ;

Try it »

When you run the above example will produce the following output-

PHP number_format Function Example

PHP number_format Function Example 3

Here is example with decimal point and separator –

Separator And String for Thousand Separator

$number = "55789.99";
$formattedNumber = number_format($number,2,',',' ');
echo $formattedNumber ;

Try it »

When you run the above example will produce the following output-

PHP number_format Function

In the above example there is comma instead of dot and a space separator in thousand.