How to Get the Number of Rows in CSV PHP

Written by mike gamble
  • Share
  • Tweet
  • Share
  • Email

Hypertext Preprocessor (PHP) is a programming language usually used for generating dynamic content for websites. Like many programming languages, PHP provides support for comma-separated values (CSV), which is a common format for storing data in regular text files. Almost all spreadsheet applications support exporting data in CSV format, and with PHP you can use that data in website applications as well. One common task associated with managing data of this sort is counting the number of records or rows.

Skill level:


  1. 1

    Open an ordinary text editor that doesn't do any rich text formatting. After entering the opening PHP tag, initialise a variable to hold the current count. For example, type the following:


    $rows = 0;

  2. 2

    Open the file in read-only mode. Loop through each of the records using the "fgetcsv" command. This command automatically parses each row according to CSV standards. For example, type the following:

    if (($fp = fopen("test.csv", "r")) !== FALSE) {

    while (($record = fgetcsv($fp)) !== FALSE) {

  3. 3

    Use the increment operator to increase the count with each iteration. For example, type the following:


  4. 4

    Close the "while" loop, the CSV file and the "if" statement. For example, type the following:




  5. 5

    Display the total count and close your PHP tag. For example, type the following:

    echo "Total rows = ".$rows;


Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.