Reputation: 939
Is it possible to remove everything before special characters including this character in array
?
For example, SUBSTR()
function is used in string
$a= ('1-160');
echo substr($a,strpos($a,'-')+1);
//output is 160
Any function for array like SUBSTR()
? (least priority to preg_replace
).
Here array is structured as following example, every index consists int
value + hyphen(-)
$a= array('1-160','2-250', '3-380');
I need to change removing every values before hyphen and hyphen also
$a= array('160','250', '380');
Actually my requirement is to sum all values after the hyphen(-)
in array. If hyphen(-)
can be removed, it can be done as
echo array_sum($a);
//output is 790
but, because of the special characters, I am generating output as following way.
$total = 0;
foreach($a AS $val){
$b = explode('-',$val);
$total += $b[1];
}
echo $total;
//output is 790
I am searching short and fast method as possible.
Upvotes: 0
Views: 257
Reputation: 2322
Although you already have the answer, this is for your reference.
array_sum(array_map(function ($item) {return explode('-', $item)[1];}, $a));
Upvotes: 1
Reputation: 6379
strstr with substr should work just fine
<?php
$a = ['1-160','2-250', '3-380'];
$result = [];
foreach($a as $b) {
$result[] = substr(strstr($b, '-'), 1); // strstr => get content after needle inclusive needle, substr => remove needle
}
var_dump($result);
var_dump(array_sum($result));
Upvotes: 1