In: Computer Science
Compare PHP code used to create and update two-dimensional arrays to another programming language. Which is easier and more efficient? Why? Can be compared to any other well used language.
I am comparing Php with Nodejs (javascript) as Nodejs is one of the most used in web development, iot in present time.
----------------------------
To create a 2d array in Php we have to write the following code :
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
To create the same 2d array in Javascript we write just this :
let cars=[["Volvo",22,18],["BMW",15,13],["Saab",5,2],["Land Rover",17,15]];
---------------------------
As we can clearly see it is much easier to create a 2d array in Javascript, We have to write just 1 line of code which is much easier to understand
------------------------
Update 2d array :
in PHP :
foreach ($cars as $k => $v) {
if ($v[0]=='Volvo') {
$cars[$k][1]=25;
$cars[$k][2]=23;
}
}
in Javascript :
cars.forEach(function(car){
if(car[0]==="Volvo"){
car[1]=25;
car[2]=23
}
})
ES6+ syntax
cars.forEach(car=>{
if(car[0]==="Volvo"){
car[1]=25;
car[2]=23
}
})
--------------------------
We can clearly see the Javascript code is really easy to learn and understand,I believe Python is also easier and more effecient than php.
We can do complex operations in 2d arrays in both Javascript and Python in a better way than Php.
Also Javascript provides lots of inbuilt higher order functions with arrays which makes the work a lot easier.
for example if we want to filter out volvo array from th 2d array we just have to write only 1 line code :-
var filteredCars=cars.filter(car=>{return car[0]!=='Volvo'})
The new variable filteredCars is free from the Volvo Array.