Skip to main content
corephp example and tutorial for beginner

30+ core PHP examples and tutorials for beginner

In the previous post we discussed that how to install PHP in windows using XAMPP. And now in this post, we move one step forward in PHP programming language. This is a list of 30+ core PHP examples and tutorials for beginner. As a developer, I would like to say new developer that please complete your basic (core) and then move to the new CMS and MVC frameworks. If your base is strong and logic is better than no one can beat you in the programming field. Here we use many basic PHP functions. All the functions are linked to its official website, so you can understand more about that function. So let’s start practicing…

Also Read : Connect MysQl with PHP step by step

Also Read : Submit form using jQuery Ajax in PHP

PHP Comments

Comments are very important to

  Single line comment:
You can create a single line comment in PHP using following way.

<?php

//This is comment.

?>

  Multi-line comment:
You can create a multi-line comment in PHP using following way.

<?php

/*comment line 1
comment line 2
comment line 3*/

?>

Print “Hello world!”

There are two functions in PHP i.e. echo() and print() will help you to print string in the PHP. Let’s see the example.

<?php
     echo "Hello world, This is my first PHP program";    //echo function
     print("Hello world, this is my first PHP program");    //print() function
?>

Add two numbers

The best thing about PHP is you don’t need to define data type of variable like ‘int’, ‘float’, ‘double’, ‘string’, etc. It will automatically detect the data type of variable. Let’s see in this example.

<?php
	$name = "Add two numbers";
	$x = 5;
	$y = 10;
	$z = $x+$y;
	echo $z;
?>

On the above example, result will be 15.

Combine two or more string in PHP

In the PHP, If you want to connect two or more string, then you can do that by using “.”(Dot Operator). Lets see the example

<?php 
$str1 = "This";
$str2 = "is";
$str3 = "PHP";
echo $str1.$str2.$str3;
?>

Calculate the length of string

Here in this example, we will use strlen() function to calculate the characters or length of string. See the below example.

<?php 
$str = "Hello PHP!";
$num = strlen($str);
echo $num;
?>

Find substring in string

This example’s logic will always use when you write a program for searching data. Here we will use strpos() function for that. Lets see the example.

<?php 
$str = "This are PHP examples";
if (strpos($str,'are') !== false) 
{
    echo 'true';
}
?>

Count a words from the string

For count a words from string we will use PHP’s inbuilt function str_word_count(). See the example here.

<?php
echo str_word_count("This is PHP examples.");
?>

Replace word from string

To replace a word from string there is str_replace() function in PHP. We will use it to perform this example. See the example.

<?php
$str = "I am PHP developer";
echo str_replace("developer","programmer",$str);
?>

Reverse a string

To perform this example, we have inbult PHP function strrev(). We will use it in the below example. See the example.

<?php
$str = "I am PHP developer";
echo str_replace("developer","programmer",$str);
?>

Define array in PHP

Array is an important part in the PHP programming. Here is a example to show you that how to define array in PHP example. Remember that array will start index from ‘0’.

<?php
$array1 = array('a','b','c','d','e');   //method 1
$array2 = ['x','y','z','w','m'];  //method 2
?>

Access the above array in PHP.

<?php
echo "Array1";
echo $array1[0]."<br>";
echo $array1[1]."<br>";
echo "Array2";
echo $array2[0]."<br>";
echo $array2[1]."<br>";
?>

Result:
Array1
a
b
Array2
x
y

Count array in PHP

To count array in PHP we use count() function of PHP. Let’s see the examples.

<?php
$array = array('a','b','c','d','e');
echo count($array);
?>

Result: 5

Multidimentional array in PHP

Multidimentional arrays are important while working in large database applications. Here in this example you will learn how to define multidimentional array. See the below example.

Name Age Adult
John 21 Yes
Marcony 25 Yes
Marry 16 No

Now, we will define above table data using array in PHP. See the below code carefully

<?php
$name = array(
	array(
		'name' => 'John',
		'age' => 21,
		'adult' => 'Yes'
		),
	array(
		'name' => 'Marcony',
		'age' => 25,
		'adult' => 'Yes'
		),
	array(
		'name' => 'Marry',
		'age' => 16,
		'adult' => 'No'
		)
	);
?>

Now How to access the multidimensional array in PHP. See the below code.

<?php
echo $name[0]['name']."<br>";
echo $name[1]['name']."<br>";
echo $name[2]['name']."<br>";
?>

Result:
John
Marcony
Mary

Same way you can access other data of multidimensional array in the PHP.

Sort array in PHP

If you have many results in the application and you want to sort them by AtoZ. Then you can do that by sort() function. See the below example.

<?php
$name = array('John', 'Marcony', 'Andrew');
$data = sort($name);
echo "<pre>";
print_r($name);
?>

Result:
Array
(
[0] => Andrew
[1] => John
[2] => Marcony
)

File operations in PHP

File operations (File I/O) are most important part of any programming language. In file operations, you are able to perform create, delete, open, close, edit, etc. See the below examples to make more sense.

Open/Close file

Consider a file named “test.txt” is inside your current root directory. There is below 5 line data inside it.
This is PHP line 1.
This is PHP line 2.
This is PHP line 3.
This is PHP line 4.
This is PHP line 5.
Now we will open this “test.txt” file using fopen PHP function. See below example. Here we use fopen(), feof(), fgets() and fclose() functions of PHP.

<?php
$file = fopen("test.txt", "r") or die("File does not open!");
while(!feof($file)) {
   echo fgets($file) . "<br>";
}
fclose($file);
?>

Result:
This is PHP line 1.
This is PHP line 2.
This is PHP line 3.
This is PHP line 4.
This is PHP line 5.

Create a new file and write some data.

Let’s create a new file and write some data inside it using PHP function. For performing this example we will use fwrite() PHP function.

<?php
$file = fopen("new.txt","w");
$txt1 = "This is text1. ";
$txt2 = "This is text2. ";
fwrite($file,$txt1);
fwrite($file,$txt2);
?>

When the above program execute it will automatically generate a new file named “new.txt” and insert two line “This is text1” and “This is test2”.

Calculate the size of file.

You may have question that how to calculate size of file using PHP. Don’t worry about it. PHP provide a inbuilt function named filesize(). Here in this example we will use filesize() function for get a size of our previous file i.e “test.txt”. See the below example.

<?php
$file = fopen("test.txt","r") or die("File does not open");
$size = filesize("test.txt");
echo $size." Bytes";
?>

Result:
103 Bytes

Encode/Decode data in json.

Json(JavaScript Object Notation) is most popular language for storing and exchanging data. It is very famous because of its simplicity. It can easily access with javascript. json_encode() and json_decode() functions available for the encode and decode task

Encode data in Json

See the below example. We will use json_encode function to encode the PHP data into json format

<?php
$data = array(
	'name' => 'John',
	'age' => 21,
	'adult' => 'Yes'
	);

echo json_encode($data);
?>

Result:
{“name”:”John”,”age”:21,”adult”:”Yes”}

Decode json data

In this example, we decode the json data using json_decode() function. See the below example.

<?php
$data = array(
	'name' => 'John',
	'age' => 21,
	'adult' => 'Yes'
	);

$new_data = json_encode($data);

echo "<pre>";
print_r(json_decode($new_data));
?>

Result:
stdClass Object
(
[name] => John
[age] => 21
[adult] => Yes
)

In this example. First we encode array data to json format using json_encode() function. After that we decode the data from json to array using json_decode() function.

Get current Date and Time using PHP

To get current Date and Time we will use date() function of PHP. See the below example.

<?php 
echo date('Y')."<br>";			// Current Year
echo date('m')."<br>";			// Current Month
echo date('d')."<br>";			// Current Date
echo date('d-m-Y')."<br>";      // Date : dd-mm-yyyy
echo date('d/m/Y')."<br>";		// Date : dd/mm/yyyy
echo date('d/m/y')."<br>";		// Date : dd/mm/yy
echo date('h')."<br>";			// Current Hour
echo date('i')."<br>";			// Current Miniut
echo date('s')."<br>";			// Current second
echo date('a')."<br>";			// AM or PM
echo date('h:i:sa');			// Time : hh:mm:ss AM/PM
?>	

Convert String to Time

We will convert string to time using strtotime() function. This is an amazing function which will help you to convert all type date-format into date-time format. Don’t understand, See the below example.

<?php
echo strtotime("now") . "<br>";                            
echo strtotime("3 October 2005") . "<br>";
echo strtotime("+5 hours") . "<br>";
echo strtotime("+1 week") . "<br>";
echo strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>";
echo strtotime("next Monday") . "<br>";
echo strtotime("last Sunday");
?>

Compile the above program into your PC and check what result flash. The above example convert string to time is courtesy of www.w3schools.com

I hope that you enjoy the article. If you like my work and think that it will helpful for others then please share it. Thanks for being here. Next time i will come up with another interesting article. Thank you!!

admin

HI, i am software developer having knowledge of PHP, C, C++ programming languages. I am very passionate about programming and ability to solve the programming problems. CodeandTuts is my blog where i like to put new tutorial and help new developer.

One thought on “30+ core PHP examples and tutorials for beginner

Leave a Reply

Your email address will not be published. Required fields are marked *