Kudos
Collect
Twiiter
Facebook
Share
Develop somethings, meditation, reading and thinking...

Foreach PHP like usage in JavaScript

Last updated about 1 year ago
1 0 0 0

Array

How to use foreach ( $brrs as $key => $value ) in PHP with JavaScript Array.

var arr = ['aaa', 'bbb', 'ccc'];

arr.forEach(function(element, key) {
    console.log('Element', key, 'is', element);
});

--- Result: ---
Element 0 is aaa
Element 1 is bbb
Element 2 is ccc

Object

How to use foreach ( $brrs as $key => $value ) in PHP with JavaScript Object (JSON).

var brr = {'a': 'aaa', 'b':'bbb', 'c':'ccc'};

for ( const [key, value] of Object.entries(brr) ) {
    console.log('Key', key, 'is', value);
}

--- Result: ---
Key a is aaa
Key b is bbb
Key c is ccc

Bonus - $crr[] = “a_data”;

How to use $crr[] = "a_data"; in PHP with JavaScript Object.

var crr = {};

crr[Object.keys(crr).length] = 'Data like PHP crr[] = "data #1"';
crr[Object.keys(crr).length] = 'Data like PHP crr[] = "data #2"';
crr[Object.keys(crr).length] = 'Data like PHP crr[] = "data #3"';

for ( const [key, value] of Object.entries(crr) ) {
    console.log('Key', key, 'is', value);
}

--- Result: ---
Key 0 is Insert data like crr[] = "data #1"
Key 1 is Insert data like crr[] = "data #2"
Key 2 is Insert data like crr[] = "data #3"

To array, you can use push function.


var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.push("Kiwi");

Reference

Hi, my name is Richard. I’m a developer wants to make the world better with logic power. Mainly I use Linux, Nginx, MySQL, PHP and JavaScript . I want to share my knowledge with someone that it was also based from some great persons via LYNMP. 👨‍💻

 

Responses

Leave a response to @richard

Please sign in to comment.
Markdown is also available in comment.