Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,627 questions

56,915 answers

573 users

How to format a string using fixed-width fields in PHP

4 Answers

0 votes
/*
Common format specifiers
-----------------------------------
%-10s // Left-aligned string, width 10
%10s // Right-aligned string, width 10
%5d // Integer, width 5
%08d // Integer, width 8, padded with zeros
%12.2f // Float, width 12, 2 decimal places
*/


/**
 * Formats a record using fixed-width fields.
 *
 * %-15s = left-aligned string, width 15
 * %10d  = right-aligned integer, width 10
 * %12.2f = right-aligned floating-point number,
 *           width 12, 2 decimal places
 */
function formatRecord(string $name, int $age, float $salary): string
{
    return sprintf(
        "%-15s%10d%12.2f",
        $name,
        $age,
        $salary
    );
}

// Store the formatted string in a variable
$result = formatRecord("Freya", 37, 98000.00);

echo $result . PHP_EOL;


/*
run:

Freya                  37    98000.00

*/

 



answered 4 days ago by avibootz
0 votes
// Left-align "Hello" in a field 10 characters wide
$result = sprintf("%-10s", "Hello");

echo "|" . $result . "|" . PHP_EOL;



/*
run:

|Hello     |

*/

 



answered 4 days ago by avibootz
0 votes
// Pad an integer with leading zeros
$result = sprintf("%08d", 123);

echo $result . PHP_EOL;



/*
run:

00000123

*/

 



answered 4 days ago by avibootz
0 votes
// Formatting a table

// Print column headers
echo sprintf("%-15s%-10s%-12s\n", "Name", "Age", "Salary");

// Print data rows
echo sprintf("%-15s%-10d%-12.2f\n", "Luke", 50, 91000.00);
echo sprintf("%-15s%-10d%-12.2f\n", "Neo", 62, 122000.00);



/*
run:

Name           Age       Salary      
Luke           50        91000.00    
Neo            62        122000.00   

*/

 



answered 4 days ago by avibootz
...