Merge data into an array then count the array values - php

I need to merge data into an array, then count the array values.
$str = '"Cat","A","A","A","A"';
$abc = [
$str,
"A",
"Cat",
"Dog",
"A",
"Dog"
];
print_r(array_count_values($abc));
Result came out:
Array ( ["Cat","A","A","A","A"] => 1 [A] => 2 [Cat] => 1 [Dog] => 2 )
But I need like this way:
Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )

This is because $str is a string and not an array. So this is added into the $abc array as one element.
You can convert in into an array with the explode function:
$str = '"Cat","A","A","A","A"';
$arr = explode(',', $str);
// So $arr is Array([0] => "Cat", [1] => "A", [2] => "A", [3] => "A", [4] => "A")
Then you need to remove the double quotes around each element.
I suggest to use the trim function, and the array_map, to apply it to each element:
$arr = array_map(function ($item) { return trim($item, '"'); }, $arr);
// $arr is Array([0] => Cat, [1] => A, [2] => A, [3] => A, [4] => A)
Then you can merge it with the rest of values:
$abc = array_merge($arr, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
// Should be Array ( [A] => 6 [Cat] => 2 [Dog] => 2 )

Well, then, don't put a string into an array and expect it to be treated as array values. Either modify the string to be an array, and merge the two arrays, or parse the string and add each value to the array.
For the latter approach, you can do something like:
$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));
$finalarray = array_merge($abc,$splitstr);
print_r(array_count_values($finalarray));

Your logic is flawed, you should first create array properly
$str = '"Cat","A","A","A","A"';
$abc = array("A","Cat","Dog","A","Dog");
$splitstr = explode(',',str_replace('"','',$str));
$finalarray = array_merge($abc,$splitstr);
print_r(array_count_values($finalarray));
Now you will get the desired result.

Because your quote-wrapped, comma-delimited string closely resembles a json string, I reckon it will be most direct/performant to just wrap the whole string in square braces, then json_decode it and spread it into the array (so that elements are injected into the array one at a time).
Code: (Demo)
$str = '"Cat","A","A","A","A"';
$abc = [
...json_decode("[$str]"),
"A",
"Cat",
"Dog",
"A",
"Dog"
];
print_r(array_count_values($abc));

you put first element as string completely. make it separate
$str = '"Cat","A","A","A","A"';
$abc=array( "Cat","A","A","A","A", "A","Cat","Dog","A","Dog");
print_r(array_count_values($abc));
Or merge array
$arr1 = ["Cat","A","A","A","A"];
$abc=array_merge( $arr1,["A","Cat","Dog","A","Dog"]);
print_r(array_count_values($abc));
Demo

You are using array_count_values to count all the values of the $abc array. However, $str is a string and not an array, but an element of the $abc array.
The simplest solutions is to convert $str into an array by removing " double quotes (with str_replace method) and splitting substrings using , as a delimiter (with explode method). This can be done just by adding a single line as shown in this snippet:
$str = '"Cat","A","A","A","A"';
// Converts $str into an array of strings
$str_array = explode(',',str_replace('"','',$str));
$abc = array_merge($str_array, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));
You can see the execution of this script in this link.

According to the PHP manual, you can use array_merge ( array $array1 [, array $... ] )
example:
$str = '"Cat","A","A","A","A"';
$abc=array_merge($str, array("A","Cat","Dog","A","Dog"));
print_r(array_count_values($abc));

Related

how to add double quotes for each array elements in php

I have an array like below format
$array = ["a, b, c, d"]
But I want to convert the array like below format
$array = ["a","b","c","d"]
I have already googling about this issue but can't get the desire solution yet.
Anybody help please ?
Try this with explode()
The explode() function breaks a string into an array.
Note: The "separator" parameter cannot be an empty string.
Note: This function is binary-safe.
$array = ["a, b, c, d"];
$array = explode(',', $array[0]);
print_r($array);
You can do it this way with explode:
$array = ["a, b, c, d"];
$array_1 = explode(', ', $array[0]);
You can explode the contents of the string at index 0 and use that as your new array. The explode function will create an array based on the delimiter specified.
$array = ["a, b, c, d"];
$array = explode(',', $array[0]);
print_r($array);
Output:
Array ( [0] => a [1] => b [2] => c [3] => d )
Here I have exploded the string in your array "a, b, c, d" based on the comma , delimiter. This means that you will get an array of elements where the comma indicates the separation between each element in the array.

clear string from commas and put it into array

I want clear all commas from string and then put all words separated with comma into array.
For me it's easy to make it in the case i have this type of string:
word1,word2,word3,word4,word5,word6
I have juste to explode them and put them into array like this:
$words = "word1,word2,word3,word4,word5,word6";
$explode = explode(",", $words);
$array = array();
foreach($explode as $word) {
$array[] = $word;
}
And here come my need:
In the case i have this kind of string what is the approch ?
word1,,word2,,,word3,word4,,,,,,,,,,,,word5,,,,word6...
The number of commas between words undefined and can be up to 100 commas.
Let me know if u have good approch to this kind of string.
The array_filter function in PHP is used for "filtering" an array i.e. making a new array from the elements of an array that satisfy a condition.
By default if we do not pass any callback to array_filter, it removes all falsey and null values. We can send a callback function as a second parameter which returns true for elements that should stay and false for elements that should be removed.
$words = "word1,word2,word3,word4,word5,word6";
$words_arr = array_filter(explode(",", $words));
print_r($words_arr);
If there is whitespace between commas, then:
$words_arr = array_filter(explode(",", $words), function ($e) {
return strlen(trim($e)) > 0; // Only select those elements which have a length > 0 after trimming
});
strlen is for getting the string length
trim is for stripping whitespace from the beginning and end of a string
use preg_split
$explode = preg_split("/,+/", $words);
First use explode as you did to get all the values:
>>> $values = explode(',', 'word1,word2,,,,word3');
>>> print_r($values);
Array
(
[0] => word1
[1] => word2
[2] =>
[3] =>
[4] =>
[5] => word3
)
Use array_filter on the solution to filter out empty results:
>>> $non_empty_values = array_filter($values);
>>> print_r($non_empty_values);
Array
(
[0] => word1
[1] => word2
[5] => word3
)
Finally, to reset the array indices, use array_values:
>>> $results = array_values($non_empty_values);
>>> print_r($results)
Array
(
[0] => word1
[1] => word2
[2] => word3
)

Remove spaces from array values

I have a string which contains numbers separated by commas. It may or may not have a space in between the numbers and a comma in the end. I want to convert it into an array, that I can do using following code:
$string = '1, 2,3,';
$array = explode(',', $string);
However the additional irregular spaces gets in the array values and the last comma causes an empty index (see image below).
How can I remove that so that I get only clean values without spaces and last empty index in the array?
Simply use array_map, array_filter and explode like as
$string = '1, 2,3,';
print_r(array_map('trim',array_filter(explode(',',$string))));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Explanation:
Firstly I've split string into an array using explode function of PHP
print_r(explode(',',$string));
which results into
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] =>
)
So we need to remove those null values using array_filter like as
print_r(array_filter(explode(',',$string)));
which results into
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Now the final part need to remove that (extra space) from the values using array_map along with trim
print_r(array_map('trim',array_filter(explode(',',$string))));
SO finally we have achieved the part what we're seeking for i.e.
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Demo
The simple solution would be to use str_replace on the original string and also remove the last comma if it exists with a rtrim so you dont get an empty occurance at the end of the array.
$string = '1, 2,3,';
$string = rtrim($string, ',');
$string = str_replace(' ', '', $string);
$array = explode(',', $string);
print_r($array);
RESULT:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
First perform following on the string -
$string = str_replace(' ', '', $string);
Then use explode.
$string = '1, 2,3,';
$array = explode(',', $string);
$array = array_filter(array_map('trim', $array));
print_r($array);
array_map is a very useful function that allows you to apply a method to every element in an array, in this case trim.
array_filter will then handle the empty final element for you.
This will trim each value and remove empty ones in one operation
$array = array_filter( array_map( 'trim', explode( ',', $string ) ) );

How to read a CSV string into an array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I split a comma delimited string into an array in PHP?
extract tags (words) from whole string
I'm trying to read a long variable into an array.
Variable $x = "text1", "text2", "text3", etc...
$x = '"text1", "text2", "text3"';
Do I just call it into my array like:
array($x)?
This doesn't seem to work
I want the final product to be:
array("text1", "text2", "text3")
What am I doing wrong? Thanks!
EDIT:
Ok, some specifics:
I'm trying to replace the date fields in the following array with many dynamically read dates:
$myCalendar->setSpecificDate(array("2012-09-09", "2012-09-10"), 1, '');
I have the dynamically read dates in a variable $x. When I echo $x, I get something in the format "2012-09-09", "2012-09-10", "2012-09-09", "2012-09-10", "2012-09-09", "2012-09-10", etc
Thanks
If your variable is a string like:
$x = '"text1", "text2", "text3"'
You can convert it to an array with str_getcsv like the following:
$x = '"text1", "text2", "text3"';
$yourArray = str_getcsv($x);
If your input string is '"text1", "text2", "text3"'
You can use the following code to get an array with three string
print_r(
explode( ",", preg_replace('/[" ]*/', "", '"text1", "text2", "text3"'))
);
// Outputs Array ( [0] => text1 [1] => text2 [2] => text3 )
This assumes there are no spaces in your strings, you'll have to play with it if spaces are allowed
Explode it. String becomes an array based on a delimiter.
$x = "text1,text2,text3";
$new_array = explode(',', $x);
This becomes:
Array
(
[0] => text1
[1] => text2
[2] => text3
)

Array_unshift like function that returns the array

is there a built in function in php that prepends an element to an array, and returns the new array?
instead of returning the new length of the array?
You could use
array_merge()
For example
$resultingArray = array_merge(array($newElement), $originalArray);
Next to array_merge, if there ain't any duplicate keys, you can do:
$array = array('a' => 'A');
$append = array('b' => 'hello');
$array = $append + $array;
Gives:
Array
(
[b] => hello
[a] => A
)
The plus is the array union operatorĀ­Docs.
There's no built-in which does it, but it's simple enough to wrap it:
function my_unshift($array, $var) {
array_unshift($array, $var);
return $array;
}
This isn't necessary though, because array_unshift() operates on an array reference so the original is modified in place. array_push(), array_pop(), array_shift() all also operate on a a reference.
$arr = array(1,2,3);
array_unshift($arr, 0);
// No need for return. $arr has been modified
print_arr($arr);
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)

Categories