3
\$\begingroup\$

I'm trying to find the shortest and best way to achieve the following:

Given input integer $N, get the following output:

  • n = 0, output = 0
  • n = 1, output = 0
  • n = 2, output = 10
  • n = 3, output = 100
  • n = 4, output = 1000
  • n = 5, output = 10000

I do this with the following code, but there must be a better option to do this.

<?php
 $n = 1;
 function getNumber($n) {
 if ($n === 0 OR $n === 1) {
 return "0";
 } else {
 return "1".str_repeat("0", $n -1);
 }
 }
 echo getNumber($n);
?>
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Mar 25, 2016 at 14:54
\$\endgroup\$
3
  • 3
    \$\begingroup\$ Just an overall comment, but calling a function 'getNumber' when it returns a string may not be the best solution to your problem \$\endgroup\$ Commented Mar 25, 2016 at 15:09
  • 3
    \$\begingroup\$ What you may and may not do after receiving answers. I've rolled back Rev 2 → 1. \$\endgroup\$ Commented Mar 25, 2016 at 15:18
  • \$\begingroup\$ Allright, won't do it again! Tnx :-) \$\endgroup\$ Commented Mar 25, 2016 at 15:19

2 Answers 2

6
\$\begingroup\$

Maybe you want something short like is

echo ($n <= 1) ? 0 : pow(10, $n - 1);
answered Mar 25, 2016 at 15:14
\$\endgroup\$
5
\$\begingroup\$

The pow function is probably what you are looking for.

return pow(10, $n-1); should be close to what you want but might need tweeking for borderline cases.

answered Mar 25, 2016 at 15:06
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.