user796443
user796443

Reputation:

Exctract minus sign from a variable

I've a peculiar situation, I need to split variable into two parts [sign] and [number]

So I can have following integers (this is not a sequence, I can have only 1 integer at a time):

-15,...,-1,0,1,...,15

When there is minus sign I need to split it into [-] part and [integer] part when there is no sign I need [+] and [integer]

How would I do this?

I was thinking to use explode with explode("-" but if there is no minus sign it will give errors... Any easy way to achieve what I want instead of writing multiple if functions?

Upvotes: 0

Views: 8673

Answers (2)

emartel
emartel

Reputation: 7773

For a single integer, you can do the following:

$singlevalue = -15;

$singlesplit = array('value' => abs($singlevalue));
if($singlevalue < 0)
    $singlesplit['sign'] = '-';
else
    $singlesplit['sign'] = '+';

print_r($singlesplit);

Which gives the output:

Array
(
    [value] => 15
    [sign] => -
)

abs here is important if you want to remove the sign of the value.

Also, if you receive your value as a string, simply use intval

$singlevalue = intval($stringValue);

Upvotes: 1

David Fells
David Fells

Reputation: 6798

$ints = '-1,2,-3,4,-5,6';
$signed_ints = explode(',', $ints);
foreach ($signed_ints as &$int) {
  if (intval($int) >= 0) {
    $int = '+' . $int;
  }
}

Upvotes: 1

Related Questions