This question already has answers here:
how to do a sum on a string in php?
(5 answers)
Closed 8 months ago.
I have a PHP string that contains numbers. Is there a way to add up all the numbers in a string?
For example: I have a string called $soc_count. That string outputs the following:
1 1
Is there a way to add up all the numbers in a string?
My code:
<?php $soc_count = [];$soc_count = (get_row_layout() == 'irl_today_social_media');?>
<?php echo $soc_count;?>
Assuming numbers are positive integers and string is not empty, you can try this:
eval('$sum = ' . trim(preg_replace('/[^0-9]+/', "+0+", $soc_count), '+') . ';');
echo $sum;
Use explode on your string of numbers, and then sum up the array:
$soc_count = "1 1";
$nums = explode(" ", $soc_count);
$total = array_sum($nums);
echo $total;
For a more general solution, which would cover a string of any type having numbers in it, we can try using preg_match_all:
$soc_count = "1 quick brown fox jumped over 1 lazy dog.";
preg_match_all("/\d+/", $soc_count, $matches);
$nums = $matches[0];
$total = array_sum($nums);
echo $total;
Related
I have rand function like;
$mynumbers = rand(1111,9999);
echo $mynumbers;
Example output is
3582
and I have another strings
$mystring = "Ja9Js78I4PhXiF464R6s7ov8IUF"; (Have 1 number, must be turn 1 (only 8 have))
$mystring2 = "Ja3Js73I4P1X5iF564R8s2ov8IUF"; (Have 4 numbers, must be turn 4 (have all of them))
And i want to know this with function ;
$mystring is have, how many numbers ? inside $mynumbers and how many time ? passed when this process ? How can i do it ?
per your last comment. Treat the integer as a string (PHP is good at that). And iterate by character.
<?php
$foo = '1234';
$mystring = [];
$mystring[] = 'A1B2KLDLDF3'; //3
$mystring[] = 'XXXX4XXXX'; //1
foreach ($mystring as $key => $string) {
echo "mystring {$key}: ";
$c = 0;
foreach(str_split($foo) as $char) {
$c = $c + substr_count($string, $char);
}
echo $c . '<br/>';
}
mystring 0: 3
mystring 1: 1
As this is PHP you also need to be aware of mb_ multibyte functions. See: http://php.net/manual/en/function.mb-substr-count.php
Update:
Sounds like you should clean up the string you are checking then if you want to discard all duplicates... Could then of course use a substr or other method perhaps more performant than substr_count.
$mystring = 'A111111B2KLDLDF333'; //3
$mystring = implode('',array_unique(str_split($mystring)));
//gives 'A1B2KLDF3'
This question already has answers here:
explode string into variables
(2 answers)
Closed 5 years ago.
I need to use php and extract the items from the string and assign them to variables.
$string = "76305203 ;124400884 ;109263187 ;current ;18.44";
How can I get:
$var1 = 76305203
$var2 = 124400884
To create variables use list()
<?php
$string = "76305203 ;124400884 ;109263187 ;current ;18.44";
list($var1,$var2) = explode(';', $string);
echo $var1;
echo PHP_EOL;
echo $var2;
Output:- https://eval.in/928536
Or use explode() to get array and use that array
<?php
$string = "76305203 ;124400884 ;109263187 ;current ;18.44";
$array = explode(';', $string);
echo $array[0];
echo PHP_EOL;
echo $array[1];
Output:-https://eval.in/928537
This question already has answers here:
concat a for loop - php
(3 answers)
Closed 2 years ago.
Is it possible to combine two strings with for loop?
For example:
echo 'Prefix '.for($i=0;$i<4;$i++){ echo $i; }.' suffix';
This is not possible:
echo 'Prefix ';
for($i=0;$i<4;$i++)
{
echo $i;
}
echo ' suffix';
Because I would like to save a page using file_put_contents and source has a combination of HTML and PHP.
I would like to get:
$page = <beginning_of_html_page_here>
<php_code_here>
<end_html_page_here>
file_put_contents(page.html, $page);
You can use string concatenation. Use the dot . to join to strings, 'a'.'b' will give 'ab'. And $a .= 'c' will append 'c' to the $a variable.
// Create the string
$string = 'Prefix ';
for($i=0;$i<4;$i++)
{
// Append the numbers to the string
$string .= $i;
}
// Append the suffix to the string
$string .= ' suffix';
// Display the string
echo $string;
Result is:
Prefix 0123 suffix
Demo at Codepad.
About the end of your question, you can use this logic:
$page = '<beginning_of_html_page_here>';
// Append things to your string with PHP
$page .= 'something'
$page .= '<end_html_page_here>';
About your first code block, this can also be done by using two functions: range() to generate an array of numbers and implode() to join the array's items:
<?php
// Create the string
$string = 'Prefix '.implode('', range(0, 3)).' suffix';
echo $string;
This question already has answers here:
Extract a single (unsigned) integer from a string
(23 answers)
Closed 7 years ago.
I have these two pieces of text
120 - 140 (cm)
and
110 (cm)
I'd like to store the values into an array like
$array[0] = 120
$array[1] = 140
$array_2[0] = 110
How would i do this?
You could do
function numArray($str)
{
$str = preg_replace("/[^0-9,.]/", " ", $str);
return preg_split('/ /', $str, -1, PREG_SPLIT_NO_EMPTY);
}
$str = "120 - 140 (cm)";
$array = numArray($str);
That will return an array with only numbers in it
Something like this?
<?php
$array = array();
$array_2 = array();
$array[0] = 120;
$array[1] = 140;
$array_2[0] = 110;
?>
I'm trying to turn MySQL data into an array and then calculate the sum of that array.
$weight = ($product['av_id_1'])*$val; // get attribute values
$weightsub = explode(" ", $weight); // convert string to array
echo array_sum($weightsub);
I'm getting an output but its not what I expected, instead of a single integer its spaced integers like "30 40 50".
Where am I going wrong?
Thanks
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo array_sum($weightsub)*$val;
First you need to extract all numbers using explode. Then apply array_sum to sum all numbers in the array, and multiply the sum by $val.
If this doesn't work as intended, you can easily do some basic debugging by using echo and print_r on each variable or result:
echo '$product[av_id_1] = <br>';
print_r($product['av_id_1']);
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo '$weightsub = <br>';
print_r($weightsub);
echo "<br>\$val = $val<br>";
echo 'Sum = ' . array_sum($weightsub) . '<br>';
echo array_sum($weightsub)*$val;