Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
php echo only first 20 characters from a variable string

I have situation, where I have to echo certain length for several variables at various locations.

I know in bash we can use echo ${variable:0:20} to achieve this, without rewriting or refining the variable.

for example in php I want to be able to do this.

$string1 = "I am looking for a way to only echo the first 20 characters from a string variable";
echo $string:0:20;

I know it is dead simple to redefine my variable in php like this and echo it.

$small = substr($big, 0, 20);
echo $small;

But I have to use the same variable at some many location and each location I have to echo different length, so it is not feasible to use the above method. Is there is something else I am missing that I could use?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I know in bash we can use echo ${variable:0:20} to achieve this, without rewriting or refining the variable.

In PHP you can use echo substr($variable, 0, 20); also without rewriting or refining the variable.

For convenience (and easy modifications, e.g. adding ... to all wrapped strings) you can wrap this in a small function:

function shorten($string, $maxLength) {
    return substr($string, 0, $maxLength);
}

and use it as

echo shorten("Some very very very very very long string", 20);

Or even include the echo in your function:

function output($string, $maxLength) {
    echo substr($string, 0, $maxLength);
}

and use it as

output("Some very very very very very long string", 20);
over 4 years ago · Santiago Trujillo Report

0

The easiest solution is to build a function so you can spare some lines of code, I don't see any other improvements you can make besides that, something like:

function small($string)
{
    return substr($string, 0, 20);
}

Use it as:

print small("Some sentence longer than 20 chars");
over 4 years ago · Santiago Trujillo Report

0

You're not missing anything but the fact that you can just echo the returned value from substr itself. If you want to go really short, like if writing the second parameter from substr is too much, just wrap it in a new function.

function
ss($string, $size)
{
    return substr($string, 0, $size);
}

echo ss('long ... string', 20);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!