php array_sum returning first value only - php

I'm fairly new at php, but this seems to be me overlooking something completely basic?
I have some values in a database column, that are comma separated like so:
1,2,3
When I try to get the sum of the values, I expect the echo of array_sum to be 6, but I only get returned the first value ie. "1"
echo $amount; //Gives 1,2,3 etc.
$amount_array = array($amount);
echo array_sum($amount_array); //Only prints "1"
print_r($amount); // shows 1,2,3
print_r($amount_array); // shows Array ( [0] => 1,2,3 )

It's a string not an array, you have to split it using explode function:
$exploded = explode ( "," , $amount_array);
var_dump($exploded);

To use the array_sum the string needs to be converted to an array
You need to use the explode function:
$amount_array = explode(',', $amount);
So you total code should be like this:
$amount_array = explode(',', $amount);
echo array_sum($amount_array);

array_sum() works by adding up the values in an array. You only have one key=>value pair in your array: key 0 with a value of 1,2,3.
If you have a comma-separated list, and want that to be an array, I would use the explode() function to turn the list into the proper key=>value pairs that array_sum() would expect.
Try
$amount_array = explode(',',$amount);

You can not initialize an array the way you intend. You are passing in a comma-separated string, which is just a single argument. PHP doesn't automagically convert that string into separate arguments for you.
In order to convert a comma-separated string into an array of individual values you can break up the string with a function like explode(), which takes a delimiter and a string as its arguments, and returns an array of the delimiter-separated values.
$amount_array = explode( ',', $amount ); // now $amount_array is the array you intended

Related

How to group foreach result the same value PHP

Please help me on how to group the value from foreach result:
foreach ($result as $value) {
$group = $value['Barcode'];
echo $group.'<br>';
}
the result of this:
9822550005004
9822550005004
9844660005002
9844660005002
9844660005002
9844660005002
My expected result would be:
9822550005004
9844660005002
You can use foreach and external array for getting the output like you want.
Using the foreach loop you need to store the each value in an array, here i store the value to the $arr array and makes the key as same as the value, cause yuo need the unique values, after storing the values just implode them with suitable delimiter space and get the desire output.
$arr = array();
foreach($result as $value){
$arr[$value['Barcode']] = $value['Barcode'];
}
echo implode(" ", $arr); //9822550005004 9844660005002
Using Array functions...
array_column Get all the columns from the array as name Barcode and makes anther array of them, After that array_unique choose the unique values from the returned array and also make another array of it. So now you need to implode them as you want. The implode method makes the array as string with a delimiter. Here i use space.
$arr = array_unique(array_column($result, "Barcode"));
echo implode(" ", $arr); //9822550005004 9844660005002

PHP make N copies of array with functions

In my code I need to make a number of copies of a dummy array. The array is simple, for example $dummy = array('val'=> 0). I would like make N copies of this array and tack them on to the end of an existing array that has a similar structure. Obviously this could be done with a for loop but for readability, I'm wondering if there are any built in functions that would make this more verbose.
Here's the code I came up with using a for loop:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
To reiterate, I'd like to rewrite this with functions if such functions exist. Something along the lines of this (obviously these are not real functions):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
I think you're looking for array_fill:
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.
So:
$newElements = array_fill(0, $n, Array('val' => 0));
You do still have to handle the appending of $newElements to $existingArray yourself, probably with array_merge:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So:
$existingArray = array_merge($existingArray, $newElements);
This all works because your top-level arrays are numerically-indexed.

Convert Array into Key Value Pair array

I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :
for instance:
array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)
into:
array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)
You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:
array(
[animals] => array(
[0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
)
)
this can be used with $array['animals'][0]
But still you need numbers or unique identifiers to access the values of the array.
Something like this:
$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);
$arrayReturn['animals'] = $array;
print_r($arrayReturn);
u cant have same key for all the values but u can do this
lets say your string is
$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
$yourArray['animals']=$animals;
}
Now it doesnot matter how long your string is you will have you array as
$yourArray['animals'][0]='dog'
$yourArray['animals'][1]='ant'
....... so on ......

change starting index when assigning one array to another in php

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.

How to find string elements in another string and remove them in PHP

By example:
FirstString='apple,gold,nature,grass,class'
SecondString='gold,class'
the Result must be :
ResultString='apple,nature,grass'
$first = explode(',',$firstString);
$second = explode(',',$secondString);
Now you have arrays and you can do whatever you want with them.
$result = array_diff($first, $second);
this is the easy way (for sure there must be more efficient ones):
First of all, you may want to separate those coma-separated strings and put them into an array (using the explode function):
$array1 = explode(',' $firstString);
$array2 = explode(',' $secondString);
Then, you can loop the first array and check whether it contents words of the second one using the in_array function (if so, delete it using the unset function):
// loop
foreach( $arra1 as $index => $value){
if( in_array ( $value , $array2 ) )
unset($array1[$index]); // delete that word from the array
}
Finally, you can create a new string with the result using the implode function:
$result = implode(',' , $array1);
That's it :D
I'm sure there is a function that can do it but you could always break up the strings and do a foreach on each one and do some string compares and build a new string. You could also break apart the second string and create a regular expression and do a preg_replace to replace the values in the string.

Categories