You are advised to check corresponding YouTube video at the end of this article.
In PHP, count()
is a built-in function that is used to count the number of elements in an array or the number of characters in a string. It returns the number of elements in an array or the length of a string.
<?php
$languages = array("Javascript", "Perl", "Lisp", "C++", "Python");
$num_of_languages = count($languages);
echo "Number of langs: " . $num_of_languages;
?>
This is a PHP script that creates an array named $languages
with five elements: "Javascript", "Perl", "Lisp", "C++", and "Python".
The count()
function is then used to count the number of elements in the $languages
array, which is five. The result is then stored in a variable called $num_of_languages
.
Finally, the script outputs the result to the screen using the echo
statement, which prints the string "Number of langs: " concatenated with the value of $num_of_languages
, which is "5" in this case.
<?php
$languages = array("Javascript", "Perl", "Lisp", "C++", "Python");
$num_of_languages = count($languages);
for ($x = 0; $x < $num_of_languages; $x = $x + 1) {
echo "Lang at the moment: $languages[$x] <br>";
}
?>
This PHP script creates an array called $languages
containing five different programming languages. It then uses the count()
function to determine the number of elements in the $languages
array and stores that value in the $num_of_languages
variable.
Next, it uses a for
loop to iterate through the array. The loop initializes the $x
variable to 0, and then loops as long as $x
is less than $num_of_languages
. Inside the loop, it uses the $x
variable to access each element of the array in turn, and then prints out a message that includes the current element of the array.
The output of this script will be five lines of text, each one displaying one of the programming languages in the $languages
array.
<?php
$languages = array("Javascript", "Perl", "Lisp", "C++", "Python");
$num_of_languages = count($languages);
foreach ($languages as $lang) {
echo "Lang at the moment: $lang <br>";
}
?>
This script uses a foreach
loop to achieve the same thingas before. The loop iterates over the $languages
array, and each time it goes through the loop, it assigns the current element's value to the variable $lang
. The loop then prints out the value of $lang
.
This is a more concise and often easier to read way of iterating over an array in PHP
No comments:
Post a Comment