PHP Count Array Elements With Specific Value
Last Updated : Jan 1, 2023
IN - PHP
In this tutorial we will show you the solution of PHP count array elements with specific value, here we are going to find user specified value in array then how many times it present in array that count is take it as result and display on webpage browser.
For achieve this we need to use inbuilt methods of count() function and array_keys() function in php. As we know manually also we can do this process.
Step By Step Guide On PHP Count Array Elements With Specific Value :-
For count specific value in array we used count() and array_keys() functions in php. The array_keys() function returns an array containing the keys.
The count() is a array class method which returns the number of elements in the array.
It can also find the total number of a particular element in the array.
First we using array_keys() method for collects specific value in array then using count() method we are able to count that specific one value appearance in array and displayed result on webpage.
<?php $arr = array("rose","green","yellow","rose","red"); $res = count(array_keys($arr,"rose")); echo "Actual array : "; print_r ($arr); echo "<br>rose counts in array : ".$res; ?>
- A php script can be placed anywhere in the document. A php script starts with <?php and end with ?>.
- The default file extension for php files is “.php” and php statements end with ‘;’ semicolon.
- We defined array and stored to variable ‘$arr’ and ‘$’ symbol must add before variable name when we define a variable in php.
- Our user defined array values are ‘ "rose","green","yellow","rose","red" ' those values before we need to declare ‘array’ word because it refers those are array values and we can give any values within array it’s our own choice.
- Another thing is one value within array must be appeared two or more times then only it counts will vary than others.
- Variable ‘$res’ contain that specific value count by using count() method, array_keys() function with two parameters, array variable and that specific value here we take it as ‘rose’ so it returns count of ‘rose’ to ‘$res’.
- Here we used echo for printing result on webpage browser first echo prints input string then another echo prints removed string as a result on webpage. In php we have more inbuilt functions for display value or string on webpage.
In conclusion we are able to know how to count specific value in array using php.
When work with php we need to create and process php files at server location and then we need to start the server before execute the program.
When we executing this program on browser it returns count of specific value (i.e ‘rose’) presents in an array as a result.
For display results on webpage value or string we can use print, alertbox or print_r methods also available in php.
I hope this tutorial on PHP count array elements with specific value helps you and the steps and method mentioned above are easy to follow and implement.