settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: How to show all elements (values) in Php array using for loop?

+6 votes

In Php I want to show all the elements in an array (meaning the values not the keys) by using for loop.

  • How can I do it?
  • Which function should I use for $i<=n?

For example I have this array:

$arr = [ 'London', 'Moscow', 'Beijing', 'New York', 'Berlin' ];

Is there a function for this task in PHP?

asked in PHP category by user nikole

2 Answers

+3 votes
 
Best answer

There is a special loop for arrays in Php (including for the associative arrays), it is called foreach.

Read MORE HERE

You should use foreach if you want to see the values in associative arrays (and not only for associative arrays
 but for simple ones as well)
.

Here's an example:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>PHP - foreach Loop</title>
</head>
<body>

<?php

$names = [
	'Alex'   => 'Alexi',
	'Connor' => 'McGregor',
	'Habib'  => 'Nurmagomedov',
	'John'   => 'Cena',
];

foreach ( $names as $name ) {
	echo $name . '<br>';
}

?>

</body>
</html>

Also, it is a good practice to name the array in plural and the value in singular.

For example if the array is named $names, the values to be shown (printed) should be named $name.

And this is the code if you want to see the keys and the values:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>PHP - For Loop</title>
</head>
<body>

<?php

$names = [
	'Alex'      => 'Alexi',
	'Connor' => 'McGregor',
	'Habib'  => 'Nurmagomedov',
	'John'   => 'Cena',
];

foreach ( $names as $key => $name ) {
	echo "$key $name" . '<br>';
}

?>

</body>
</html>
answered by user Jolie Ann
selected by user golearnweb

Also you will freaquntly see this:

foreach ( $arr as $k => $v ) {
	echo "$k $v" . '<br>';
}

Where

$k stands for key in the array

and

$v is the value if in the array

+4 votes

You can use count function. (line #3)

Here is only the php code:

$arr = [ 'London', 'Moscow', 'Beijing', 'New York', 'Berlin' ];

for ( $i = 0; $i < count( $arr ); $i++ ) {
	echo $arr[ $i ] . '<br>';
}

And the whole code in HTML:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>PHP show array values with For Loop</title>
</head>
<body>

<?php

$arr = [ 'London', 'Moscow', 'Beijing', 'New York', 'Berlin' ];

for ( $i = 0; $i < count( $arr ); $i++ ) {
	echo $arr[ $i ] . '<br>';
}

?>

</body>
</html>

 

answered by user icabe
It will work ONLY if your keys are known and in order; For Associative Arrays in PHP - you must use foreach loop: https://www.w3schools.com/php/php_arrays.asp
...