How can I add all of my array values together in PHP? Is there a function for this?
If your array consists of numbers, you can use array_sum to calculate a total. Example from the manual:
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
If your array consists of strings, you can use implode:
implode(",", $array);
it would turn an array like this:
strawberries
peaches
pears
apples
into a string like this:
strawberries,peaches,pears,apples
if your array are all numbers and you want to add them up, use array_sum(). If not, you can use implode()
array_sum function should help. Here I presume your array comprises of integer or float values.
Let the given array values may contain integer or may not be.
It would be better to have check and filter the values.
$array = array(-5, " ", 2, NULL, 13, "", 7, "\n", 4, "\t", -2, "\t", -8);
// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'is_numeric' );
echo array_sum($result);
Related
I have a string
$tailored_information="3, 5, 10, 13, 7, 6";
Now I have need to make an array like
$input_array = array("Id" => 3, "Id" => 5);
I am using this but not work cause i cant add key ID
explode(",", $tailored_information)
As been told, you can't have array with the same key, because it is a hash table, which will override the "id" every time.
I suggest you to use simply
explode(", ", $id_array);
or
explode(", ", $another_arr['id']);
like this you will group the data by id...
If you wish to go into some more complicated - you could create your own data structure, which will be non-unique array - where you will divide different values by key...
this way the print version will be whatever you want...
An array has to have unique keys. Also, you will now have spaces in your values
What you could do is explode by ", " and then take that array as your array straight away. If the key you want/need is always "Id" then it doesn't matter anyway.
<?php
$abc = "3, 5, 10, 13, 7, 6";
$new_array = explode(',',$abc);
$new_id_array = array();
foreach($new_array as $key=>$val){;
$new_id_array[$key]['id'] = $val;
}
print_r($new_id_array);
?>
you can not put same key in a array key. so for that you have to create a nested array.and that will solve ur problem and now you can have same array key, but in different arrays.OR
$abc = "3, 5, 10, 13, 7, 6";
$new_array = explode(',',$abc);
foreach($new_array as $key=>$val){
$new_id_array['id_'.$key] = $val;
}
I am trying to use sizeof or count to return the number of things inside the array, however whenever I use the $rank_ids2 to count rather than entering 1, 2, 3, 4, 67, 7 in manually, it just returns 1, but when I type them in the array directly, it counts 6 just fine!
$ranksAllowed = '|1|2|3|4|67|7|';
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
$rank_ids2 = implode(", ", $rank_ids);
$arrayofallowed = array($rank_ids2);
echo sizeof($arrayofallowed);
$rank_ids is just turning the |1|2|.. format into 1, 2
My first solution to your problem would be to initially define $ranksAllowed as an array instead of a pipe-character-delimited string:
$ranksAllowed = array(1, 2, 3, 4, 67, 7);
This would make more sense in almost any foreseeable situation. If for some reason you'd rather keep $ranksAllowed as a string...
Some simplification
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
can be simplified to:
$rank_ids = explode('|', trim($ranksAllowed, '|'));
Decide on string or array format
Right now it looks like you're trying to do 2 things at once (and achieving neither)
One possibility is you want to turn your pipe-delimited ("|1|2|3|...") string into a comma delimited string (like "1, 2, 3, ..."). In this case, you could simply do a string replace:
$commaDelimited = str_replace('|', ',', trim($ranksAllowed, '|'));
The other possibility (and I believe the one you're looking for) is to produce an array of all the allowable ranks, which you've already accomplished in an earlier step, but assigned to $rank_ids instead of $arrayofallowed:
$arrayofallowed = explode('|', trim($ranksAllowed, '|'));
//Should print out data in array-format, like you want
print_r($arrayofallowed);
//Echo the length of the array, should be 6
echo count($arrayofallowed);
implode converts an array to a string, so after everything you get this:
A string named $ranksAllowed that contains |1|2|3|4|67|7|
An array named $rank_ids that contains multiple elements, being them 1, 2, etc...
A string named $rank_ids2 that contains 1,2,3,4,67,7
An array named $arrayofallowed with only 1 element, being it the string inside $rank_ids2
To achieve a string that contains 1,2,3,4,67,7 from |1|2|3|4|67|7| you can just trim the | character as you do and replace | with ,. Is less CPU expensive.
$rank_ids2 = str_replace("|", ",", trim("|".$ranksAllowed."|", '|'));
If you want to count them you can explode it and count the elements:
$rank_ids2_array = explode(',', $rank_ids2);
echo sizeof($rank_ids2_array);
or with your code you can simply count the already exploded $rank_ids.
echo sizeof($rank_ids);
Try something like the following:
$ranksAllowed = '|1|2|3|4|5|67|7|';
$rank_ids = explode('|', trim($ranksAllowed, '|'));
echo count($rank_ids);
Just to explain the above, the $arrayofallowed is imploding the array of $rank_ids, creating a string. This will not give you the expected results when counted. If you simply count the $rank_ids (as explode() will leave you with an array), you should see the desired result of 7 items.
The $rank_ids is your array, and $arrayofallowed was a string.
Please see the sections of the PHP manual related to the implode() and explode() functions for more information.
I have the following fairly simple code, where I need to determine if a certain value exists in an array:
$testvalue = $_GET['testvalue']; // 4
$list = '3, 4, 5';
$array = array($list);
if (in_array($testvalue, $array)) { // Code if found } else { // Code if not found }
Even though it is obvious that the number 4 is in the array, the code returns the code inside the else bracets. What have I done wrong?
Change the third line:
$array = array_map('trim', explode(',',$list));
$array here is:
$array = array('3, 4, 5');
which is not the same as:
$array = array(3, 4, 5);
So, fix the way you are creating this array.. don't do it from a string.
Your array contains just one value, the string 3, 4, 5.
See the example on CodePad.
If you want to convert your string in an array, you can use:
$array = explode(', ', $list);
I have added a space behind the comma, but a safer method would be to use just a comma and then trim all values.
I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.
$arr = array('1st', '1st');
The above $arr has 2 items , I want to repeat $arr so that it's populated with 4 items
Is there a single call in PHP?
array_fill function should help:
array array_fill ( int $start_index, int $num, mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
In your case code will look like:
$arr = array_fill(0, 4, '1st');
$arr = array('1st', '1st');
$arr = array_merge($arr, $arr);
This is a more general answer. In PHP 5.6+ you can use the "splat" operator (...) to repeat the array an arbitrary number of times:
array_merge(...array_fill(0, $n, $arr));
Where $n is any integer.