about php... how to convert string to array then show out? - php

i have this string -
$result = "ABCDE";
and i want to seperate them to 3 parts
(like part 1 = A, part 2 = B, part 3 = C..., part 5 = E)
,give a name to each of them
part 1(A) = Apple
part 2(B) = Orange
part 3(C) = Ice-cream
part 3(D) = Water
part 5(E) = Cow
then the finally output is like
Output : You choose Apple, Orange, Ice-cream, Water, Cow
or like this
$result = "ACE";
Output : You choose Apple, Ice-cream, Cow
i have tried using array
$result = "ABCDE";
$showing = array(A => 'Apple , ', B => 'Orange , ', C => 'Ice-cream , ',
D => 'Water , ', E => 'Cow , ');
echo $showing[$result];
but i got nothing while output, seems array is not working in fixed string.
i want to know how to do it

For one line magic:
echo implode('',array_intersect_key($showing,array_flip(str_split($result))));

You can use the function str_split to split the string into individual letters, which can later be used as keys of your associative array.
Also you don't need to add comma at the end of each string. Instead you can use the implode function to join your values:
$input = "ABCDE";
$showing = array('A' => 'Apple', 'B' => 'Orange', 'C' => 'Ice-cream',
'D' => 'Water', 'E' => 'Cow');
$key_arr = str_split($input);
$val_arr = array();
foreach($key_arr as $key) {
$val_arr[] = $showing[$key];
}
echo "You choose ".implode(',',$val_arr)."\n";

You can access characters from a string similar to elements in an array, like this:
$string = "ABCDE";
echo $string[2]; // "C"
Technically, it's not really treating it like an array, it just uses a similar syntax.
You could use
$choices= array('A' => 'Apple', 'B' => 'Orange', 'C' => 'Ice-cream',
'D' => 'Water', 'E' => 'Cow');
$selected[] = array();
for ($i = 0, $len = strlen($result); $i < $len; $i++) {
$selected[] = $choices[$string[$i]];
}
echo "You have selected: " . implode(', ', $selected);
Although str_split, as others have suggested, would also work.

Related

exploding string with multiple delimiter [duplicate]

This question already has answers here:
PHP - split String in Key/Value pairs
(5 answers)
Convert backslash-delimited string into an associative array
(4 answers)
Closed 12 months ago.
i have a string like
$str = "1-a,2-b,3-c";
i want to convert it into a single array like this
$array = [
1 => "a",
2 => "b",
3 => "c"
];
what i do is
$str = "1-a,2-b,3-c";
$array = [];
$strex = explode(",", $str);
foreach ($strex as $str2) {
$alphanumeric = explode("-", $str2);
$array[$alphanumeric[0]] = $alphanumeric[1];
}
can i do this in a better way?
You can use preg_match_all for this:
<?php
$str = "1-a,2-b,3-c";
preg_match_all('/[0-9]/', $str, $keys);
preg_match_all('/[a-zA-Z]/', $str, $values);
$new = array_combine($keys[0], $values[0]);
echo '<pre>'. print_r($new, 1) .'</pre>';
here we take your string, explode() it and then preg_match_all the $value using patterns:
/[0-9]/ -> numeric value
/[a-zA-Z]/ -> letter
then use array_combine to get it into one array
Thanks to u_mulder, can shorten this further:
<?php
$str = "1-a,2-b,3-c";
preg_match_all('/(\d+)\-([a-z]+)/', $str, $matches);
$new = array_combine($matches[1], $matches[2]);
echo '<pre>'. print_r($new, 1) .'</pre>';
just a little benchmark:
5000 iterations
Debian stretch, php 7.3
parsed string: "1-a,2-b,3-c,4-d,5-e,6-f,7-g,8-h,9-i"
[edit] Updated with the last 2 proposals [/edit]
You can use preg_split with array_filter and array_combine,
function odd($var)
{
// returns whether the input integer is odd
return $var & 1;
}
function even($var)
{
// returns whether the input integer is even
return !($var & 1);
}
$str = "1-a,2-b,3-c";
$temp = preg_split("/(-|,)/", $str); // spliting with - and , as said multiple delim
$result =array_combine(array_filter($temp, "even", ARRAY_FILTER_USE_KEY),
array_filter($temp, "odd",ARRAY_FILTER_USE_KEY));
print_r($result);
array_filter — Filters elements of an array using a callback function
Note:- ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value
array_combine — Creates an array by using one array for keys and another for its values
Demo
Output:-
Array
(
[1] => a
[2] => b
[3] => c
)
One way to do with array_map(),
<?php
$my_string = '1-a,2-b,3-c';
$my_array = array_map(function($val) {list($key,$value) = explode('-', $val); return [$key=>$value];}, explode(',', $my_string));
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($my_array)) as $k=>$v){
$result[$k]=$v;
}
print_r($result);
?>
WORKING DEMO: https://3v4l.org/aYmOH
Tokens all the way down...
<?php
$str = '1-a,2-b,3-c';
$token = '-,';
if($n = strtok($str, $token))
$array[$n] = strtok($token);
while($n = strtok($token))
$array[$n] = strtok($token);
var_export($array);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
Or perhaps more terse without the first if...:
$array = [];
while($n = $array ? strtok($token) : strtok($str, $token))
$array[$n] = strtok($token);
Not a better way but one more example:
$str = "1-a,2-b,3-c";
$arr1 = explode(",", preg_replace("/\-([a-zA-Z]+)/", "", $str));
$arr2 = explode(",", preg_replace("/([0-9]+)\-/", "", $str));
print_r(array_combine($arr1, $arr2));
Mandatory one-liner (your mileage may vary):
<?php
parse_str(str_replace([',', '-'], ['&', '='], '1-a,2-b,3-c'), $output);
var_export($output);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
You can do one split on both the , and -, and then iterate through picking off every other pair ($k&1 is a check for an odd index):
<?php
$str = '1-a,2-b,3-c';
foreach(preg_split('/[,-]/', $str) as $k=>$v) {
$k&1 && $output[$last] = $v;
$last = $v;
}
var_export($output);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
The preg_split array looks like this:
array (
0 => '1',
1 => 'a',
2 => '2',
3 => 'b',
4 => '3',
5 => 'c',
)
This one explodes the string as the OP has on the comma, forming the pairs: (1-a) and (2-b) etc. and then explodes those pairs. Finally array_column is used to create the associated array:
<?php
$str = '1-a,2-b,3-c';
$output =
array_column(
array_map(
function($str) { return explode('-', $str); },
explode(',', $str)
),
1,
0
);
var_export($output);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)

How to convert Array to string in PHP without using implode method?

I Have an Array like this,
$arr = array_diff($cart_value_arr,$cart_remove_arr);
I Want to convert it to string without using implode method anyother way is there? And Also i want to remove $cart_remove_arr from $cart_value_arr the array_diff method i used it is correct?
You can use json_encode
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
This will also work on multi dimensional arrays
Will result to:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Doc: http://php.net/manual/en/function.json-encode.php
Another way is the classic foreach plus string concatenation
$string = '';
foreach ($arr as $value) {
$string .= $value . ', ';
}
echo rtrim($string, ', ');
Yet another way is to use serialize() (http://php.net/manual/en/function.serialize.php), as simple as...
$string = serialize($arr);
This can handle most types and unserialize() to rebuild the original value.
$cart_remove_arr = array(0 => 1, 1=> 2, 2 => 3);
$cart_value_arr = array(0 => 5, 1=> 2, 2 => 3, 3 => 4, 4 => 6);
$arr = array_diff($cart_value_arr, $cart_remove_arr);
echo '<pre>';
print_r($arr);
$string = "";
foreach($arr as $value) {
$string .= $value.', ';
}
echo $string;
**Output: Naveen want to remove $cart_remove_arr from $cart_value_arr
Remaining array**
Array
(
[0] => 5
[3] => 4
[4] => 6
)
he want a similar out as implode()
**String** 5, 4, 6,

php display random value from key on array

I have array which have in letter format key.
'A' => array('WORD1','WORD2','WORD3'),
'B' => array('WORD1','WORD2','WORD3'),
'C' => array('WORD1','WORD2','WORD3'),
'D' => array('WORD1','WORD2','WORD3'),
'E' => array('WORD1','WORD2','WORD3'),
'F' => array('WORD1','WORD2','WORD3'),
'H' => array('WORD1','WORD2','WORD3'),
'G' => array('WORD1','WORD2','WORD3'),
...
I need to pick random value from each element. Example, when I set $output = "FGH"
Output will be:
F - (RANDOM WORD FROM ARRAY KEY F)\n
G - (RANDOM WORD FROM ARRAY KEY F)\n
H - (RANDOM WORD FROM ARRAY KEY H)\n
I used my code below but doesn't work..
$result = array();
foreach($chars as $char){
$random_key = array_rand($words[$char]); // get random key
$key = $words[$char][$random_key]; // get the word
unset($words[$char][$random_key]); // unset it so that it will never be repeated
$result[$key] = $char; // push it inside
}
Thanks to anyone that would help me
This gives a random word from whichever keys are specified in $output (note I have modified your $chars array slightly to make it obvious which value is being returned):
$chars = array(
'A' => array('A_WORD1','A_WORD2','A_WORD3'),
'B' => array('B_WORD1','B_WORD2','B_WORD3'),
'C' => array('C_WORD1','C_WORD2','C_WORD3'),
'D' => array('D_WORD1','D_WORD2','D_WORD3'),
'E' => array('E_WORD1','E_WORD2','E_WORD3'),
'F' => array('F_WORD1','F_WORD2','F_WORD3'),
'G' => array('G_WORD1','G_WORD2','G_WORD3'),
'H' => array('H_WORD1','H_WORD2','H_WORD3')
);
$output = 'FGH';
$result = array();
foreach(str_split($output) as $key) {
$result[] = $chars[$key][array_rand($chars[$key])];
}
var_dump($result);
The secret sauce here is the str_split() function.
<?php
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,3);
echo $a[$random_keys[0]]."<br>";
echo $a[$random_keys[1]]."<br>";
echo $a[$random_keys[2]];
?>
for your reference : http://php.net/manual/en/function.array-rand.php
If you have already set up the random arrays to pick words from, it's quite straight forward with count() and rand().
//$globalWordArray = .......;
$selectedArray = array('B','D','F');
$wordList = array();
foreach($selectedArray as $words){
$wordList[] = $globalWordArray[$words][rand(0,count($globalWordArray[$words])-1];
}
This could be a solution:
$letters = array(
'A' => array('WORD1','WORD2','WORD3'),
'B' => array('WORD1','WORD2','WORD3'),
'C' => array('WORD1','WORD2','WORD3'),
'D' => array('WORD1','WORD2','WORD3'),
'E' => array('WORD1','WORD2','WORD3'),
'F' => array('WORD1','WORD2','WORD3'),
'H' => array('WORD1','WORD2','WORD3'),
'G' => array('WORD1','WORD2','WORD3'),
);
$output = "FGH";
for ($i=0; $i < strlen($output); $i++) {
echo $output[$i] ." - (RANDOM WORD FOR ARRAY KEY " . $output[$i]." ";
echo $letters[$output[$i]][array_rand($letters[$output[$i]])] .")" . "<br />";
}
Output is:
F - (RANDOM WORD FOR ARRAY KEY F WORD3)
G - (RANDOM WORD FOR ARRAY KEY G WORD3)
H - (RANDOM WORD FOR ARRAY KEY H WORD1)
Your logic looks wrong where you are actually performing the randomisation, see comments in your code below
$result = array();
foreach($chars as $char){
$random_key = array_rand($words[$char]);
$key = $words[$char][$random_key]; // This is a value at this point yet you named it key
unset($words[$char][$random_key]);
$result[$key] = $char; // This will create an entry in result such as $result['WORD 1'] = 'F', I'm sure thats wrong
}
Fixed version below
$result = array();
foreach($chars as $char){
$random_key = array_rand($words[$char]);
$value = $words[$char][$random_key];
unset($words[$char][$random_key]);
$result[$char] = $value;
}
What you have suggested you want is commonly referred to as a Shuffle Bag (http://kaioa.com/node/89). Shuffle Bags allow you to fill up collections with items and then pick them out randomly until the collection runs out of items. Think of it like the Bag of letters in Scrabble. There is a PHP implementation in the link above.
Using that sort of implementation would turn your foreach loop to this:
$result = array();
foreach($chars as $char){
$result[$char] = $words[$char]->next();
}

PHP find n-grams in an array

I have a PHP array:
$excerpts = array(
'I love cheap red apples',
'Cheap red apples are what I love',
'Do you sell cheap red apples?',
'I want red apples',
'Give me my red apples',
'OK now where are my apples?'
);
I would like to find all the n-grams in these lines to get a result like this:
cheap red apples: 3
red apples: 5
apples: 6
I tried to implode the array and then parse it, but it's stupid because new n-grams can be found because of the concatenation of strings that have nothing to see between each other.
How would you proceed?
I want to find group of words without knowing them before although
with your function I need to provide them before anything
Try this:
mb_internal_encoding('UTF-8');
$joinedExcerpts = implode(".\n", $excerpts);
$sentences = preg_split('/[^\s|\pL]/umi', $joinedExcerpts, -1, PREG_SPLIT_NO_EMPTY);
$wordsSequencesCount = array();
foreach($sentences as $sentence) {
$words = array_map('mb_strtolower',
preg_split('/[^\pL+]/umi', $sentence, -1, PREG_SPLIT_NO_EMPTY));
foreach($words as $index => $word) {
$wordsSequence = '';
foreach(array_slice($words, $index) as $nextWord) {
$wordsSequence .= $wordsSequence ? (' ' . $nextWord) : $nextWord;
if( !isset($wordsSequencesCount[$wordsSequence]) ) {
$wordsSequencesCount[$wordsSequence] = 0;
}
++$wordsSequencesCount[$wordsSequence];
}
}
}
$ngramsCount = array_filter($wordsSequencesCount,
function($count) { return $count > 1; });
I'm assuming you only want repeated group of words.
The ouput of var_dump($ngramsCount); is:
array (size=11)
'i' => int 3
'i love' => int 2
'love' => int 2
'cheap' => int 3
'cheap red' => int 3
'cheap red apples' => int 3
'red' => int 5
'red apples' => int 5
'apples' => int 6
'are' => int 2
'my' => int 2
The code could be optimized to, for instance, use less memory.
The code provided by Pedro Amaral Couto above is very good.
Since I use it for French, I modified the regular expression as follows:
$sentences = preg_split('/[^\s|\pL-\'’]/umi', $joinedExcerpts, -1, PREG_SPLIT_NO_EMPTY);
This way, we can analyze the words containing hyphens and apostrophes ("est-ce que", "j'ai", etc.)
Try this (using the implode, since that's you've mentioned as an attempt):
$ngrams = array(
'cheap red apples',
'red apples',
'apples',
);
$joinedExcerpts = implode("\n", $excerpts);
$nGramsCount = array_fill_keys($ngrams, 0);
var_dump($ngrams, $joinedExcerpts);
foreach($ngrams as $ngram) {
$regex = '/(?:^|[^\pL])(' . preg_quote($ngram, '/') . ')(?:$|[^\pL])/umi';
$nGramsCount[$ngram] = preg_match_all($regex, $joinedExcerpts);
}
Assuming you just want to count the number of occurrences of a string:
$cheapRedAppleCount = 0;
$redAppleCount = 0;
$appleCount = 0;
for($i = 0; $i < count($excerpts); $i++)
{
$cheapRedAppleCount += preg_match_all('cheap red apples', $excerpts[$i]);
$redAppleCount += preg_match_all('red apples', $excerpts[$i]);
$appleCount += preg_match_all('apples', $excerpts[$i]);
}
preg_match_all returns the number of matches in a given string so you can just add the number of matches onto a counter.
preg_match_all for more information.
Apologies if I misunderstood.

How to split a comma separated string into groups of 2 each and then convert all these groups to an array

I have a string which is like 1,2,2,3,3,4 etc. First of all, I want to make them into groups of strings like (1,2),(2,3),(3,4). Then how I can make this string to array like{(1,2) (2,3) (3,4)}. Why I want this is because I have a array full of these 1,2 etc values and I've put those values in a $_SERVER['query_string']="&exp=".$exp. So Please give me any idea to overcome this issue or solve.Currently this is to create a group of strings but again how to make this array.
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{
$result[] = sprintf('%d,%d', array_shift($buffer), array_shift($buffer));
}
return implode(',', $result);
}
$result = x($expr);
but its not working towards my expectations
I'm not sure I completely understand. You can create pairs of numbers like:
$string = '1,2,3,4,5,6';
$arr = array_chunk(explode(',', $string), 2);
This will give you something like:
array(
array(1, 2),
array(3, 4),
array(5, 6)
)
If you wanted to turn them into a query string, you'd use http_build_query with some data massaging.
Edit: You can build the query like this (100% UNtested):
$numbers = array_map(function($pair) {
return array($pair[0] => $pair[1]);
}, $arr);
$query_string = '?' . http_build_query($numbers);
This:
echo '<pre>';
$str = '1,2,3,4,5,6,7,8';
preg_match_all('/(\d+,\d+)(?=,*)/', $str, $matches);
$pairs = $matches[0];
print_r($pairs);
Outputs:
Array
(
[0] => 1,2
[1] => 3,4
[2] => 5,6
[3] => 7,8
)

Categories