Asked  7 Months ago    Answers:  5   Viewed   43 times

I need to design a function to return negative numbers unchanged but should add a + sign at the start of the number if its already no present.

Example:

Input     Output
----------------
+1         +1
1          +1
-1         -1

It will get only numeric input.

function formatNum($num)
{
# something here..perhaps a regex?
}

This function is going to be called several times in echo/print so the quicker the better.

Update:

Thank you all for the answers. I must tell the sprintf based solution is really fast.

 Answers

95

You can use regex as:

function formatNum($num){
    return preg_replace('/^(d+)$/',"+$1",$num);
}

But I would suggest not using regex for such a trivial thing. Its better to make use of sprintf here as:

function formatNum($num){
    return sprintf("%+d",$num);
}

From PHP Manual for sprintf:

An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.

Wednesday, March 31, 2021
 
Strae
answered 7 Months ago
83

You can use preg_match as:

if(preg_match('/rank=(d+)/',$RankStr,$m)) {
 $rank = $m[1];
}

Code in Action

Wednesday, March 31, 2021
 
VieStar
answered 7 Months ago
35

Check out regex 101. It is a wonderfull Tool to create regular expressions and understand them. From there i got this solution for you:

%^d{1,2}:d{1,2}([ap])m[(Mon|Tue|Wed|Thu|Fri|-){1,} Only]$%mg

The first bit (d{1,2}) accepts a number between 0 and 99, then a : and another number between 0 and 99. Then it is either a or p followed by m. Then you have either Mon or Tue or .... or - for 1 to endles times.

At the end you have the modifiers g and m. The m is to make use of the ^ and $ modifiers that represent the beginning and the end of a line. The g is just to find ALL results rather than the first existing. You can leave that out.

To use Weekdays from an array called $array simply implode it to a string and fill it into your expression like this:

$weekdaysString = implode('|',$array);
$regex = '%^d{1,2}:d{1,2}([ap])m[('.$weekdaysString.'|-){1,} Only]$%mg';

Read up on implode.

Saturday, May 29, 2021
 
Asher
answered 5 Months ago
91
for x in numbers:
    print "{:10.4f}".format(x)

prints

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • The empty string before the colon means "take the next provided argument to format()" – in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.
Tuesday, June 1, 2021
 
LOKESH
answered 5 Months ago
85

New answer

Re your revised question: foreach actually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:

$data = json_decode($json);
foreach ($data as $name => $value) {
    // This will loop three times:
    //     $name = inbox
    //     $name = sent
    //     $name = draft
    // ...with $value as the value of that property
}

Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a "firstName" property, this code:

$data = json_decode($json);
foreach ($data as $name => $value) {
    echo $name . ':'
    foreach ($value as $entry) {
        echo '  ' . $entry->firstName;
    }
}

...will show:

inbox:
  Brett
  Jason
  Elliotte
sent:
  Issac
  Tad
  Frank
draft:
  Eric
  Sergei

Old answer(s)

Begin edit Re your comment:

Now I would like to know how to decode JSON string with several objects!

The example you posted does have several objects, they're just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:

{"name": "I'm the first object"},
{"name": "I'm the second object"}

That JSON is not valid. There has to be a single top-level object. It might just contain an array:

{"objects": [
    {"name": "I'm the first object"},
    {"name": "I'm the second object"}
]}

...or of course you can give the individual objects names:

{
    "obj0": {"name": "I'm the first object"},
    "obj1": {"name": "I'm the second object"}
}

End edit

Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it's not much different from the example in the question you linked (which also has an object with properties that have array values).

So:

$data = json_decode($json);
foreach ($data->programmers as $programmer) {
    // ...use $programmer for something...
}
foreach ($data->authors as $author) {
    // ...use $author for something...
}
foreach ($data->musicians as $musician) {
    // ...use $musician for something...
}
Wednesday, June 30, 2021
 
hohner
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :