PHP: Array Convert comma separated string to int - php

I just tried to parse my array that contains numbers separated with comma into numbers without the comma, but still in array form. But it didn't work.
My code:
$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
print_r($arrTot);
Array result:
Array
(
[0] => 10,000
[1] => 100,000
[2] => 200,000
)
My desired output was to erase the comma in all number:
Array
(
[0] => 10000
[1] => 100000
[2] => 200000
)
I've tried with something just like this but it seems not even close with my desired output:
$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
for ($i=0; $i < count($arrTot); $i++) {
$valTot=str_replace( ',', '', $arrTot[$i]);
print_r($valTot);
}
Is there any way to solve this problem?
Thanks.

You can use array_walk to process each of the values in the array:
$arrTot = array('10,000', '100,000', '200,000');
array_walk($arrTot, function (&$v) {
$v = str_replace(',', '', $v);
});
print_r($arrTot);
Output:
Array
(
[0] => 10000
[1] => 100000
[2] => 200000
)
Demo on 3v4l.org

you might assign new value to current variable.
$arrTot = array_filter(array_slice($total, 20));
for ($i=0; $i < count($arrTot); $i++) {
$arrTot[$i]=str_replace( ',', '', $arrTot[$i]);
}
print_r($arrTot);

If you want the desired output, you need to replace the elements in the main array without comma.
$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
foreach ($arrTot as $key => $aTot) {
$arrTot[$key] = str_replace(',','',$arrTot[$i);
}
var_dump($arrTot);

Try this-
echo "<pre>";
$arr = array('10,000','100,000','200,000');
print_r($arr);
//result
Array
(
[0] => 10,000
[1] => 100,000
[2] => 200,000
)
foreach ($arr as $key => $value) {
$new[] = str_replace(',','',$value);
}
print_r($new);
Array
(
[0] => 10000
[1] => 100000
[2] => 200000
)

try this ,
$arr = ['10,000','100,000','200,000'];
foreach($arr as $key=>$val){
$arr[$key] = (int)str_replace(',','',$val);
}
var_dump($arr);

You could simply use str_replace to achieve desired result
$arrTot = array('10,000', '100,000', '200,000');
foreach($arrTot as $key => $value){
$arrTot[$key] = str_replace(",","",$value);
}
print_r($arrTot);

Related

Count how many times a value appears in this array?

I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.
array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));
Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}
You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);

Explode array's data and make new array

I have this array:
Array
(
[0] => Array
(
[0] => 1
[1] => a,b,c
)
[1] => Array
(
[0] => 5
[1] => d,e,f
)
)
I want the final array to be this:
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 1
[1] => b
)
[2] => Array
(
[0] => 1
[1] => c
)
[3] => Array
(
[0] => 5
[1] => d
)
[4] => Array
(
[0] => 5
[1] => e
)
[5] => Array
(
[0] => 5
[1] => f
)
)
This is what I did:
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count] = $arr;
$temp[$count][1] = $row;
$count++;
}
}
print_r($temp);
?>
This totally works but I was wondering if there was a better way to do this. This can be very slow when I have huge data.
Try like this way...
<?php
$array = array(array(1,"a,b,c"),array(5,"d,e,f"));
$temp=array();
$count = 0;
foreach($array as $arr){
$rows = explode(",",$arr[1]);
foreach($rows as $row){
$temp[$count][] = $arr[0];
$temp[$count][] = $row;
$count++;
}
}
/*print "<pre>";
print_r($temp);
print "<pre>";*/
?>
Here's a functional approach:
$result = array_merge(...array_map(function(array $a) {
return array_map(function($x) use ($a) {
return [$a[0], $x];
}, explode(",", $a[1]));
}, $array));
Try it online.
Or simply with two loops:
$result = [];
foreach ($array as $a) {
foreach (explode(",", $a[1]) as $x) {
$result[] = [$a[0], $x];
}
}
Try it online.
Timing these reveals that a simple loop construct is ~8 times faster.
functional: 4.06s user 0.08s system 99% cpu 4.160 total
loop: 0.53s user 0.05s system 102% cpu 0.561 total
If you need other way around,
$array = array(array(1, "a,b,c"), array(5, "d,e,f"));
$temp = [];
array_walk($array, function ($item, $key) use (&$temp) {
$second = explode(',', $item[1]);
foreach ($second as $v) {
$temp[] = [$item[0], $v];
}
});
print_r($temp);
array_walk — Apply a user supplied function to every member of an array
Here is working demo.

PHP foreach() loop

$string = "The complete archive of The New York Times can now be searched from NYTimes.com " //the actual input is unknown, it would be read from textarea
$size = the longest word length from the string
I assigned and initialized array in for loop, for example array1, array2 ....arrayN, here is how i did
for ($i = 1; $i <= $size; $i++) {
${"array" . $i} = array();
}
so the $string would be divided in the length of the word
$array1 = [""];
$array2 = ["of", "be", ...]
$array3 = ["the", "can", "now", ...] and so on
So, my question is how to assign in simple for loop or foreach loop $string value to $array1, $array2, $array3 ....., since the input text or the size of the longest word is unknown
I'd probably start with $words = explode(' ', $string)
then sort the string by word length
usort($words, function($word1, $word2) {
if (strlen($word1) == strlen($word2)) {
return 0;
}
return (strlen($word1) < strlen($word2)) ? -1 : 1;
});
$longestWordSize = strlen(last($words));
Loop over the words and place in their respective buckets.
Rather than separate variables for each length array, you should consider something like
$sortedWords = array(
1 => array('a', 'I'),
2 => array('to', 'be', 'or', 'is'),
3 => array('not', 'the'),
);
by looping over the words you don't need to know the maximum word length.
The final solution is as simple as
foreach ($words as $word) {
$wordLength = strlen($word);
$sortedWords[ $wordLength ][] = $word;
}
You could use something like this:
$words = explode(" ", $string);
foreach ($words as $w) {
array_push(${"array" . strlen($w)}, $w);
}
This splits up $string into an array of $words and then evaluates each word for length and pushes that word to the appropriate array.
you can use explode().
$string = "The complete archive of The New York Times can now be searched from NYTimes.com " ;
$arr=explode(" ",$string);
$count=count($arr);
$big=0;
for ($i = 0; $i < $count; $i++) {
$p=strlen($arr[$i]);
if($big<$p){ $big_val=$arr[$i]; $big=$p;}
}
echo $big_val;
Just use the word length as the index and append [] each word:
foreach(explode(' ', $string) as $word) {
$array[strlen($word)][] = $word;
}
To remove duplicates $array = array_map('array_unique', $array);.
Yields:
Array
(
[3] => Array
(
[0] => The
[2] => New
[3] => can
[4] => now
)
[8] => Array
(
[0] => complete
[1] => searched
)
[7] => Array
(
[0] => archive
)
[2] => Array
(
[0] => of
[1] => be
)
[4] => Array
(
[0] => York
)
[5] => Array
(
[0] => Times
)
)
If you want to re-index the main array use array_values() and to re-index the subarrays use array_map() with array_values().

Combine two arrays together

I have an array that looks like this:
array
(
[name] => name
[description] => description here
[first] => Array
(
[0] => weight
[1] => height
)
[second] => Array
(
[0] => 20 kg
[1] => 50 cm
)
[company_id] => 1
[category_id] => 7
)
what function will allow me to combine these into something that looks like the following?
array
(
[together]
(
[0] => weight 20kg
[1] => height 50cm
)
)
Update
For that current array you need to use the loop.
$first = $second = array();
foreach($yourArray as $key => $array) {
if(in_array($key, array('first', 'second')) {
$first[] = $array[0];
$second[] = $array[1];
}
}
$final['together'] = array($first, $second);
According to the first array
You can try this -
$new = array(
'together' => array(
implode(' ', array_column($yourArray, 0)), // This would take out all the values in the sub arrays with index 0 and implode them with a blank space
implode(' ', array_column($yourArray, 1)), // Same as above with index 1
)
);
array_column is supported PHP >= 5.5
Or you can try -
$first = $second = array();
foreach($yourArray as $array) {
$first[] = $array[0];
$second[] = $array[1];
}
$final['together'] = array($first, $second);
you also can try array_map as below
function merge($first,$second)
{
return $first ." ".$second;
}
$combine = array_map('merge', $yourArray[0],$yourArray[1]);

Find in array and get count of each string

I am fetching some data from the db and then push them to an array. I need to find the count of some strings and print out the result (count) in an efficient way:
Array
(
[0] => q1-1,q2-2,q3-2,q4-1,q5-2,q6-3,q7-1,q8-4,
[1] => q1-1,q2-2,q3-1,q4-3,q5-3,q6-3,q7-2,q8-1,
[2] => q1-1,q2-1,q3-1,q4-1,q5-1,q6-2,q7-2,q8-2,
[3] => q1-3,q2-1,q3-1,q4-1,q5-2,q6-3,q7-1,q8-1,
[4] => q1-2,q2-2,q3-3,q4-1,q5-3,q6-3,q7-1,q8-1,
[5] => q1-1,q2-2,q3-3,q4-1,q5-2,q6-3,q7-1,q8-1,
[6] => q1-3,q2-1,q3-1,q4-3,q5-2,q6-3,q7-2,q8-4,
[7] => q1-2,q2-2,q3-3,q4-1,q5-2,q6-5,q7-1,q8-1,
[8] => q1-1,q2-1,q3-2,q4-3,q5-3,q6-5,q7-1,q8-1,
[9] => q1-2,q2-1,q3-1,q4-1,q5-3,q6-3,q7-1,q8-1,
[10] => q1-3,q2-2,q3-3,q4-3,q5-4,q6-3,q7-1,q8-1,
...
)
Sample data is above.
I need to know how many occurences of q1-1, q1-2 ... q8-4 is in the array and print out readable version. Ex. The are 23: q1-1, 412: q1-2 and so on.
I was going to create an array of each string that needs to be searched that iterate through the array. For every result increment the resultVariable for that string but I'm not sure if that's the best way.
Suggestions?
Pretty simple, loop on your array, create sub arrays, and create a counter array:
$counts = array () ;
foreach ( $your_array as $row ) {
$sub = explode(',', $row);
foreach ( $sub as $subval ) {
if ( array_key_exists ( $subval, $counts ) ) {
$counts[$subval] ++ ;
} else {
$counts[$subval] = 1 ;
}
}
}
Here is $counts:
Array (
'q1-1' => 23,
'q1-2' => 9,
// and so on....
);
Try:
$arr = array(...); //your array
$count = array();
foreach($arr as $v) {
$substr = explode(',', $v);
foreach($substr as $m) {
if(strstr($v, $m) !== FALSE)
$count[$m]++;
}
}
Printing the counts,
foreach($count as $k => $v)
echo "Count for '$k': ". $v;

Categories