I have this in PHP:
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
foreach ($arreglo as $key => $value) {
}
Is it possible to operate these values in the string? like 128 + 250 + 220, using foreach ? Thank you in advance.
If the strings always follow that format, then yes. You could explode the strings into arrays:
$a = explode(' ', $string); // Now $a[0] contains the number
So, for your code:
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$total = 0;
foreach ($arreglo as $value) { // $key not necessary in this case
$a = explode(' ', $value);
$total += $a[0]; // PHP will take care of the type conversion
}
Or, if you are feeling creative:
$func = function($s) {
$a = explode(' ', $s);
return $a[0];
};
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$numbers = array_map($func, $arreglo);
$total = array_sum($numbers);
use the below code:
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$arr = array();
$i = 0;
foreach ($arreglo as $key => $value)
{
$expVal = explode(" ",$vaulue);
$arr[$i] = $expVal[0]; //this array contains all your numbers 128, 250 etc
}
$sum = 0;
foreach($arr[$i] as $num)
{
$sum = $sum+$num
}
echo $sum; // your final sum result is here
You can do with basic PHP functions:
Working example:
<?php
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$str = implode(',', $arreglo);
$str = str_replace(' gigas', '', $str);
$n = explode(',', $str);
$count = array_sum($n);
echo $count; // Outouts 598
?>
If the space between the numbers and letters are always there, you can do this
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$total = 0;
foreach ($arreglo as $value) {
$total += strstr($value, " ", true);
}
echo "Total : $total"; // int(598)
Try this...
<?php
$total=0;
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
foreach ($arreglo as $key => $value) {
$total +=intval(preg_replace('/[^0-9]+/', '', $value), 10);
}
echo $total;
?>
You can do it using array_map() ,str_replace() and array_sum()
Working Example:
<?php
$data = array('128 gigas', '250 gigas', '220 gigas');
$data = array_map(function($value) { return str_replace(' gigas', '', $value); }, $data);
echo array_sum($data);
?>
Explanation:
1) You have an array with string values. These values contain numbers also.
2) You need to sum all the numbers.
3) Use array_map()
to replace all non-numeric characters from the string by using str_replace()
.
4) Now, use array_sum() to sum total.
If you want inline code
echo array_sum(str_replace(" gigas","",$arreglo));
You can simply use floatval() php function to get the float value from a string. Hope this helps.
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$sum=0;
foreach( $arreglo as $value ){
$sum += floatval($value);
}
print $sum;
try this
<?php
$arreglo = array('128 gigas', '250 gigas', '220 gigas');
$sum=0;
foreach ($arreglo as $key => $value) {
$sum+=(int)$value;
}
echo $sum;
?>