Related
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));
I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.
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
)
$str="a,b,c,d-e,f,g,h"
I am trying to extract the strings from $str that are separated "," and are before "-" in one array and the strings separated by "," and are after "-" in second array. So that $arr1=array(a,b,c,d); and $arr2=array(e,f,g,h);. I am just using $str as an example and generally I want this to work for any string of the same form i.e. $str=s1,s2,s3,s4,s5,....-r1,r2,t3....
NOTE: If $str doesn't have "-" then $arr2 vanishes and $arr1 contains an array of the elements separated by ',' in $str.
This is what I tried
preg_match_all('~(^|.*,)(.*)(,.*|\-|$)~', $str, $arr1);
preg_match_all('~(-|.*,)(.*)(,.*|$)~', $str, $arr2);
However each array comes with one element that contains the string str.
Does anyone know why this is not working.
All of your regex patterns are not optimal and it seems the task is easier to solve with explode and array_map:
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
$str="a,b,c,d-e,f,g,h";
$ex = array_map(function ($s) {
return explode(",", $s);
}, explode("-", $str));
print_r($ex);
See IDEONE demo
Results:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
[1] => Array
(
[0] => e
[1] => f
[2] => g
[3] => h
)
)
^(.*?(?=-|$))|(?<=-)(.*$)
You can use this to get 2 arrays.See demo.
https://regex101.com/r/vV1wW6/19
Your regex is not working as you have used greedy modifier..*, will stop at the last instance of ,
EDIT:
Use this is you want string after - to be in second group.
^(.*?(?=-|$))(?:-(.*$))?
https://regex101.com/r/vV1wW6/20
You can simply use preg_match to check does your string contains - if yes than can simply use array_walk like as
$str = 'a,b,c,d-e,f,g,h';
$result = [];
if(preg_match('/[-]/', $str)){
array_walk(explode('-',$str),function($v,$k)use(&$result){
$result[] = explode(',',$v);
});
}else{
array_walk(explode(',',$str),function($v,$k)use(&$result){
$result[] = $v;
});
}
print_r($result);
Without regex (the most reasonable way):
$str="a,b,c,d-e,f,g,h";
list($arr1, $arr2) = explode('-', $str);
$arr1 = explode(',', $arr1);
if ($arr2)
$arr2 = explode(',', $arr2);
else
unset($arr2);
With regex (for the challenge):
if (preg_match_all('~(?:(?!\G)|\A)([^-,]+)|-?([^,]+),?~', $str, $m)) {
$arr1 = array_filter($m[1]);
if (!$arr2 = array_filter($m[2]))
unset($arr2);
}
Example :
Array
(
[0] => "example.fr", "2013-08-24", "test"
[1] => "toto.com, "2014-10-01", "test2"
)
How can I do to split this array every comma ? I would like to get every word in quotes into a variable like this :
$var1= "example.fr";
$var2= "2013-08-24";
$var3 = "test";
....
EDIT: The structure of the array is GOOD ! Every element is enclosed in quotes in ONLY one array ! Like CSV file
Don't reinvent a CSV parser, use the existing functionality.
From PHP 5.3+:
$parsed = array_map('str_getcsv', $array);
http://php.net/str_getcsv
Before 5.3:
$fh = fopen('php://temp', 'r+');
$parsed = array();
foreach ($array as $row) {
ftruncate($fh, 0);
fwrite($fh, $row);
rewind($fh);
$parsed[] = fgetcsv($fh);
}
fclose($fh);
You can use list
array("example.fr, 2013-08-24, test")
list($var1, $var2, $var3) = explode(', ', $array[0]); // or current
Unless I'm misunderstanding you, you can access the array elements and assign them to variables like this:
$var1 = $arrayName[0][0];
$var2 = $arrayName[0][1];
$var3 = $arrayName[0][2];
I can't tell from you're question if the array is holding a single string per index or if it is a 2D array. If it's holding strings then see realshadow's answer.
Use explode on every item of the array: http://www.w3schools.com/php/func_string_explode.asp
I don't think your syntax is quite right to create a multidimensional array, consider this example:
$myArray = array( array("example.fr", "2013-08-24", "test"),
array("toto.com, "2014-10-01", "test2"));
Now you have an array of arrays and can iterate over each.
If you know for sure how many items you have in each array then you can explode the array into its constituents, but if you don't know before hand than iterating will see you through.
I am not very sure with the structure, but let me know if this is what ur looking for, happy to help u then -
<?php
$myarr = array( array("example.fr", "2013-08-24", "test"),array("toto.com", "2014-10-01", "test2"));
foreach($myarr as $breakpart)
{
echo "<pre>";
print_r($breakpart);
}
OUTPUT -
Array
(
[0] => example.fr
[1] => 2013-08-24
[2] => test
)
Array
(
[0] => toto.com
[1] => 2014-10-01
[2] => test2
)
Codepad Link - codepad.org/6S7EMldq