Look at the example code below and try to understand yourself what is synchronous and asynchronous ?

temp.txt file contains Hello world and we are going to read the file in javascript and PHP.

Simple text file

PHP [synchronous ] :

Reading a temp.txt file in javascript and calculating sum from 1 to 100.

<?php

$fileContents = file_get_contents('temp.txt');
if ($fileContents === false) {
    echo "Error reading file.";
    return;
}
echo $fileContents ."\n";

$sum = 0;
for ($i = 1; $i < 100; $i++) {
    $sum = $sum + 1;
}

echo $sum ."\n";

?>

First it prints the hello world from the file and then it will calculate sum 1 to 100.

Output of sync_example.php

Javascript code [ Asynchronous ]

Doing the same operation in javascript.

const fs = require('fs');

fs.readFile('temp.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(data);
});

var sum = 0
for (let i = 1; i < 100; i++) {
    sum = sum + i
}

console.log(sum) ]

First it prints the sum from 1 to 100 and then it will print hello world from the file.

Output of async_example.js

Why it's printing the hello world second 🤔 ?

Both JavaScript and PHP are interpreted languages that require their respective interpreters to read files line by line. Due to their asynchronous nature, JavaScript is capable of running multiple processes within a single thread, while PHP can achieve a similar effect using external libraries.

Difference between PHP and Javascript.

However, there are libraries and extensions available for PHP that provide asynchronous functionality, and It's important to note that the asynchronous capabilities provided by these libraries are not native to PHP and it's native to Javascript.