30+ core PHP examples and tutorials for beginner

corephp example and tutorial for beginner

In the previous post, we discussed that how to install PHP in windows using XAMPP. Now in this post, We will practice some core PHP examples related to array, if..else conditions, loops and arithmatic operations.

This is a list of 30+ core PHP examples and tutorials for beginner. As a developer, I would suggest you that please complete your basic (core) first and then move to the CMS(Content Management System) or MVC(Model View Controller) frameworks. If your base is clear than you will not face any problem.

Here i have used many core PHP functions. All the functions are linked to its official website, so you will get more clarification about that function. Without spending much time on extra stuff, let’s do practicing.

PHP Comments

Comments are very important to define your code so other developers can understand your code. In PHP, We can write two type comments as shown below.

Single line comment

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

<?php
echo phpinfo(); //This is comment.
?>

Multi-line comment

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

<?php
echo "I am developer";
/*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 and perform the operation. Let’s see in this example. tiktok takipçi satın al

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

On the above example, Result will be 15.

Related:  Simple PHP CRUD tutorial with DEMO Example

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). Check below 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

In this example, we will use strpos() function for that. Check below example.

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

Count a words from the string

To 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];
echo $array1[1];

echo "Array2";
echo $array2[0];
echo $array2[1];

?>

Result:
Array1
a
b
Array2
x
y

Count array in PHP

To count array values in PHP we use count() function of PHP. Let’s see the examples. Count function will result number of all array values.

<?php

$array = array('a','b','c','d','e');
echo count($array);

?>

Result: 5

Multidimensional array in PHP

Multidimensional arrays are important while working in large database applications. Here in this example you will learn how to define multidimensional 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 Lets see, 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

Related:  [Demo] Submit HTML Form Using jQuery Ajax in PHP

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 A to Z. 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. To 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 file. Check below example.

<?php

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

?>

Result:
103 Bytes

Related:  How To Connect MySQL with PHP [Step By Step]

Encode/Decode data in json.

Json(JavaScript Object Notation) is most popular data format for storing and exchanging data. 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:

// Json format
{
   "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 above list of core php examples. If you like it 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!!

About Chintan Panchal

I am web developer having 6+ year of experience of web development. Currently working on laravel and have worked on codeigniter, cakephp, symfony. Thank you :)

View all posts by Chintan Panchal →

2 Comments on “30+ core PHP examples and tutorials for beginner”

  1. Thanks for sharing this step by step information about PHP and read your complete post, you have explained in really very understanding method so keep posting such informative blog post.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.