Limited Offer
60% OFF on all plans!

Console Input & Output in PHP

Learn how to print output to the console and read user input from the command line in PHP using echo, print, fwrite, and readline.

Console Output Basics

Console output means showing text in the terminal. PHP provides several ways to print output — `echo` is the most common, but there is also `print`, `var_dump()`, and `print_r()`. These are essential for debugging and building CLI scripts.

1. echo (Basic Output)

`echo` is a language construct (not a function) that prints one or more strings. It is the standard way to output text in PHP.

2. Printing Variables (String Interpolation)

PHP interpolates variables directly inside double-quoted strings — no concatenation needed.

3. print vs echo

`print` is similar to `echo` but always returns `1`, making it usable inside expressions.

4. var_dump() and print_r()

These functions are invaluable for debugging — they reveal the type and structure of any value.

Printing Without Newline (fwrite / ob)

By default, `echo` does not add a newline. For CLI tools you sometimes need to write to `STDOUT` directly without any automatic buffering, or capture output into a variable using output buffering (`ob_start`).

1. fwrite(STDOUT) — Direct Terminal Write

`fwrite(STDOUT, ...)` writes directly to the terminal standard output stream, identical to `echo` but explicit.

2. Output Buffering (ob_start)

Capture `echo` output into a variable instead of printing it immediately.

3. Formatted Table Output (sprintf)

`sprintf()` formats a string using placeholders — perfect for aligning CLI table columns.

Console Input (Reading User Data)

PHP CLI scripts can accept input in two ways: 1. `$argv` — values passed as command-line arguments when running the script. 2. `readline()` — prompts the user and waits for them to type something interactively.

1. $argv (Command-Line Arguments)

Run `php app.php Raj 25` and read those values inside the script via `$argv`.

2. readline() — Interactive Input

`readline()` prompts the user and pauses until they press Enter.

3. Reading a Number

`readline()` always returns a string — cast it to a number and validate before use.

4. Reading Multiple Space-Separated Values

The user types `10 20 30` — split the string and convert each part to a number.