search

PHP array length

Aug 29, 2024 pm 12:44 PM
php

PHP array length is defined as an array which is used to get many elements on them. Using the count () function and size of (), we could able to retrieve the count of an element. An array contains either string or integer values which can be either single or multi-dimensional. The array is used to hold a value in a key-value pair, an indexed array with many in-built functions for array processing. Using two Right functions (pre-defined) here saves a lot of time in calculating the values.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

PHP array length is defined as follows:

Count(array name, mode);

This function takes two parameters, namely array name followed by a mode that denotes the dimensions. An empty array denotes zero and returns ‘1’ for non-array values.

How does array length Work in PHP?

Array length is determined by the count and size of the function. As per the syntax, the optional mode argument is set to count() recursively, which will recursively count the number of elements in an array. This function is intensively used in Multi-dimensional array.

To know an array length, we have a few common reasons:

  • Using a ‘for’ loop to move through the elements.
  • No of the search elements returned.
  • Calculating average values in an array.

But in PHP, to get the number of elements in an array, either sizeof or count function is enabled here to predict the array length in PHP. As the number of elements changes concerning user requirements in our code, it is very important to see the actual length of the array list. PHP has two in-built functions, namely count and size of.

Using count (): To count the elements.

We can use like this:

Code:

$a1=array(6,3,1,9);
echo " The size is given as =", count($a1);

So here, a count function returns the number of elements in an Object and simply counted in an associative array. In the above sample code, we have used a one-dimensional array. We have used PHPs native function count, so when we execute the above snippets, the output of the function is ‘4’. This is how we can get the values.

The second case is when we count the elements using parameter mode, to perform this, we have passed a constant ‘recursive’ as a parameter to count the elements. In this case, the length of an array is determined differently.

Code:

$avar = array (2,6,7, array (19,18,60));
$nelem = count ($avar, COUNT_RECURSIVE);
echo $nelem;

The above code displays the output as ‘7’ instead of the value ‘6’.

To perform iteration in array elements, we can use for-loop for iteration. The values should loop continues to execute. So, in each iteration step, the value gets incremented by 1. Care should be taken when using for loop in count () method as PHP lacks in differentiating indexed array and associative array. But most programmer developers pretend to use count () instead of sizeof() as it returns the memory size. Even though it is similar to the count () function, most of them stick to the count() function.

Examples of PHP array length

Two methods define PHP array length or size count. Let’s see how these methods used to determine the length in the following examples.

Example #1

Creating a simple array to count the elements.

Code:

<?php $flowers= ['Jasmine', 'Diasy', 'Rose'];
echo "The count is: " . count($flowers);
?>

Explanation:

  • When we execute the above code snippets, the output is shown as ‘3’ as the array elements have 3 elements.
  • First, we had created an array of ‘flowers’, and in the next line, we used the count command.

Output:

PHP array length

Example #2

Code:

<?php $program = [
'C++' => ['Polymorphism', 'Inheritance', 'Template'],
'Java' => ['Interface', 'Multithread', 'Exception'],
'PHP' => ['ArrayLength', 'Count']
];
echo "No. of count: ". count($program)."<br>";
echo "Multidimensional count: ". count ($program, 1);
?>

Explanation:

  • Determines an array length with the count of ‘1’.

Output:

PHP array length

Example #3

Code:



<?php $bike=array
(
"Hero Splender"=>array
(
"HP2345",
"HS3456"
),
"Royal Enfield"=>array
(
"R3",
"Tr5"
),
"Honda Activa 6G"=>array
(
"Classic 250"
)
);
echo "General count: " . sizeof($bike)."<br>";
echo "Recursive Number: " . sizeof($bike,1);
?>

Explanation:

  • The above code determines the General count as ‘3’ and the array length of recursive mode to be ‘8’.

Output:

PHP array length

Example #4

Using For-loop.

Code:

<?php $arr_iter = array (26,60,70,10,130,67);
echo "No of elements in the array = ", sizeof($arr_iter), "<br /><br>";
//Iterating through the array
for ($k=0; $k <sizeof echo of elements are:></sizeof>";
}
?>

Explanation:

  • The above code takes the length of an array using the sizeof function, and the array elements are iterated using for-loop.
  • The output shows the list of values in an array in each iteration.

Output:

PHP array length

Example #5

Using Null value in mode.

Code:

<?php $m[0] = 2;
$m[1] = 6;
$m[2] = 8;
value_res(count($m));
$n[3]  = 1;
$n[4]  = 3;
$n[8] = 5;
value_res(count($n));
value_res(count(null));
value_res(count(false));
?>

Explanation:

  • The above code returns a parameter array as the value is assigned as null. So the output looks like this.

Output:

PHP array length

Example #6

Array length Using 2D array.

Code:

<?php $foods = array('choclates' => array('Diary Milk', 'Cadbury Godiva', 'Nestle','Snikkers',
'Candy Craze'), 'Fast Food' => array('Nuggets', 'Salad Platters'));
echo count($foods, 1);
echo "";
echo sizeof($foods, 1);
?>

Explanation:

  • In the above code, we have used mode count as ‘1’; therefore, this multi-dimensional array counts the value as ‘9’.

Output:

PHP array length

Example #7

Word Count.

Code:

<?Php $stringtype=' This is EDUCBA Asia largest Web Learning Platform providing courses in various Domains. We Provide Certification from many Leading Universities across the globe.';
$my1_array=explode(" ",$stringtype);
echo "No.Of words in the String = ".sizeof($my1_array);
?>

Explanation:

  • The above program Stores a paragraph in a variable of type String.
  • Here an array is created using explode function to split the array.
  • Finally, count the number of words in a paragraph.
  • We get the count as below.

Output:

PHP array length

Conclusion

Here we have seen how to determine the length or size of an array in PHP and also the various methods to show how PHP functions are used to take memory size used by the array. There is no difference between the count and size of the function. Depends upon the developer, the methods are picked while writing the code. In this article, we explored PHP’s array length with many examples, and also, we have also seen more about multi-dimensional arrays.

The above is the detailed content of PHP array length. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft