Using PHP Array in Javascript

If you have a PHP Array and want to perform some javascript operations by looping the PHP Array, then I recommend you to use PHP foreach loop instead of Javascript forEach loop.


function myfunction() {

<?php foreach($myArray as $val) { ?>

console.log('<?=$val;?>');

<?php } ?>

}

 

Merging and Sorting two arrays in PHP

Suppose we have two PHP arrays. Now if we want to merge these two array, then there is a function in PHP to do this. Just use the below code to merge two arrays in PHP.


$combinedArray = array_merge($firstArray, $secondArray);

The above code will return a new combined array of the two arrays.

Now if we want to sort this new array, then :


foreach($combinedArray AS $val) {

$dates[] = strtotime($val['date']);  // here 'date' is the key in our $firstArray and $secondArray and our new array will be sorted according to this.

}

array_multisort($dates, SORT_ASC, $combinedArray);

Note :- Both the arrays $firstArray and $secondArray must have the ‘date’ key, because the new array $combinedArray will be sorted according to this.

Using SQL IN Operator with PHP Array

Using SQL IN operator with PHP array

Suppose we have a array named ‘id_array’ which contains id’s. Now, in order to get all the records from our MySQL table using this array of id, we can use the below given code :


SELECT * FROM TABLE WHERE id IN (".implode(',',$id_array).")