$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().
Related
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);
I am using PHP 7.3.5 and I have the following set of array values:
$valueArr = ['-4.2%', '51.0', '90K', '0.5%', '0.74|2.6', '-1.2B', '779B', '215K', '92.2%', '42.8B', '1.49T', '1690B', '-10.8B', '0.38|3.9', '102.4', '1.00%', '0.07|1.3'];
Basically I want for each of these values the number and the "type", so if it is a percentage then I would like to get -4.2 and percentage.
I tried to create a minimum example (however the below code is no real good example ;( ), but I am stuck at the data structure level as some array keys have two inputs, such as '0.74|2.6':
<?php
$valueArr = ['-4.2%', '51.0', '90K', '0.5%', '0.74|2.6', '-1.2B', '779B', '215K', '92.2%', '42.8B', '1.49T', '1690B', '-10.8B', '0.38|3.9', '102.4', '1.00%', '0.07|1.3'];
$resArr = array();
$structureArr = array(
'value1' => "",
'number1' => "",
'value2' => "",
'number2' => ""
);
foreach ($valueArr as $key => $v) {
if (1 === preg_match('/%/', $valueArr[$key])) {
preg_match('!\d+\.*\d*!', $valueArr[$key], $structureArr['number1']);
$structureArr['value1'] = 'percentage';
}
/*
if (1 === preg_match('|', $valueArr[$key])) {
$str = explode("|", $valueArr[$key]);
$value1 = 'number';
$number1 = $str[0];
$value2 = 'number';
$number2 = $str[1];
}
if (1 === preg_match('', $valueArr[$key])) {
}
*/
array_push($resArr, $structureArr);
}
print_r($resArr);
/*
Wanted Result
Array
(
[0] => Array
(
[0] => -4.2
[1] => 'percentage'
)
[1] => Array
(
[0] => 51.0
[1] => 'number'
)
[2] => Array
(
[0] => 90000
[1] => number
)
[3] => Array
(
[0] => 0.5
[1] => percentage
)
[4] => Array
(
[0] => 0.74
[1] => number
[2] => 2.6
[3] => number
)
...
*/
I would highly appreciate your input on how to structure this array input.
Appreciate your replies!
If you join the array on a space and replace pipes | with a space, then you have a list of numbers and their symbol (if any) separated by a space. Then just match your numbers and whatever symbol comes after it. Then you just match the number index with the symbol index. I used an array to map the symbol to the word and number if none:
$string = str_replace('|', ' ', implode(' ', $valueArr));
preg_match_all('/([\d.-]+)([^\s]*)/', $string, $matches);
$types = ['%'=>'percent','K'=>'thousand','M'=>'million','B'=>'billion','T'=>'trillion'];
foreach($matches[1] as $k => $v) {
$t = $types[$matches[2][$k]] ?? 'number';
$result[] = [$v, $t];
}
This yields an array like this, with each number that was joined by a pipe with it's own element:
Array
(
[0] => Array
(
[0] => -4.2
[1] => percent
)
[1] => Array
(
[0] => 51.0
[1] => number
)
[2] => Array
(
[0] => 90
[1] => thousand
)
///etc...
If you need a floating point number then just change:
$result[] = [(float)$v, $t];
This expands on my comment. Not sure if it's the most optimal solution or not.
Rough outline...
Create array mapping suffix to multiplier. Loop through source array. explode on |. Loop through result. If last character is %, strip it, value=value and type=percentage, else, strip last char, use it as array index (if it is an available index), value=value*multiplier and type=number.
$resArr = array();
$multipliers = array("K" => 1000, "M" => 1000000, "B" => 1000000000, "T" => 1000000000000);
$valueArr = ['-4.2%', '51.0', '90K', '0.5%', '0.74|2.6', '-1.2B', '779B', '215K', '92.2%', '42.8B', '1.49T', '1690B', '-10.8B', '0.38|3.9', '102.4', '1.00%', '0.07|1.3'];
foreach($valueArr as $index => $value)
{
$parts = explode("|", $value);
$resArr[$index] = array();
foreach($parts as $part)
{
$lastChar = substr($part, -1);
if($lastChar == "%")
{
$resArr[$index][] = substr($part, 0, -1);
$resArr[$index][] = "percentage";
}
else if(in_array($lastChar, array_keys($multipliers)))
{
$multiple = $multipliers[$lastChar];
$resArr[$index][] = (substr($part, 0, -1))*$multiple;
$resArr[$index][] = "number";
}
else
{
$resArr[$index][] = $part;
$resArr[$index][] = "number";
}
}
}
var_dump($resArr);
DEMO
I do not know how to change or convert the array or if I am doing something wrong in my function?
I get this array, the number is words count:
[Food] => 1
[squid] => 1
[next] => 1
[leggings] => 1
In the end, I need this array without the words count:
[0] => Food
[1] => squid
[2] => next
[3] => leggings
That's my function:
$theString_1 = "$request->body, $request->titel, $request->articleText";
// delete special character
$theString_end = preg_replace("/[^a-zA-Z 0-9 ä ü ö]+/", "", $theString_1 );
// array of each word in the content separated by 'space'.
$wordsArray = explode(' ', $theString_end);
// count words with more than 3 charakters in texts
$arrayCount = array_count_values(array_filter($wordsArray, function($v) {
return strlen($v) > 3;
}));
//sort array most used word
arsort($arrayCount);
//get 4 most used word from the array
$end = array_slice($arrayCount, 0,4);
You have two options:
The simplest one:
$array = array_keys($end);
The second one:
$array = [];
foreach($end as $key=>$value) {
$array[] = $key;
}
Hope it helps.
I need to get numbers as an array from a given string.
Example string:
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
Expected output:
if I search -T the output needs to be like this:
array(
[0] => 2,
[1] => 6
)
if it's -P:
array(
[0] => 1,
[1] => 3
)
I tried var_export(explode("-T,",$t)); but it didn't work as expected.
Can any one give me a suggestion to get this?
The below matches the full integer number which preceeds the search term -P.
Let's keep it concise:
$matches = array();
if (preg_match_all('/([0-9]+)\-P/', $t, $matches) >= 1) {
var_dump($matches[1]);
}
Search for '/([0-9]+)\-P/, '/([0-9]+)\-C/, '/([0-9]+)\-T/ an so on.
A more dynamic way to look for different search terms/filters:
$filter = '-T';
$pattern = sprintf('/([0-9]+)%s/', preg_quote($filter));
See preg_match_all and preg_quote functions.
Try this:
$t = '211111111131-P,2-T,3654554-P,4-R,5-C,6-T,';
$find = "-P"; // Search element
$found = []; // Result array
$array = explode(",", $t); // Breaking up into array
foreach($array as $arr) {
if (strpos($arr, $find)) { // Checking if search element is found in $arr
$found[] = explode('-',$arr)[0]; // Extracting the number prefix e.g 1 for 1-P
}
}
Output:
Array
(
[0] => 1
[1] => 3
)
Use it as
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$data = explode(",", $t);
print_r($data);
$row=array();
for ($i = 0; $i <= count($data); $i++) {
if (!empty($data[$i])) {
if (strpos($data[$i], '-T') !== false) {// pass find value here
$final = explode("-", $data[$i]);
$row[]=$final[0];
}
}
}
print_r($row);
Output
Array
(
[0] => 2
[1] => 6
)
DEMO
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$temp = [];
// if the last comma is not typo the 3rd argument `-1` omit empty item
$array = explode(",", $t, -1);
foreach($array as $arr) {
list($v, $k) = explode('-', $arr);
$temp[$k][] = $v;
}
print_r($temp['T']);
demo
Lots of good answers here already, but none take the approach of first putting the data into a better structure.
The code below converts the data to an associative array mapping letters to arrays of numbers, so that you can then do repeated lookups by whichever letter you want:
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$a = array_filter(explode(',', $t));
$map = [];
foreach($a as $item) {
$exploded = explode('-', $item);
$number = $exploded[0];
$letter = $exploded[1];
if (!array_key_exists($letter, $map)) {
$map[$letter] = [];
}
$map[$letter][] = $number;
}
print_r($map);
// Array
// (
// [P] => Array
// (
// [0] => 1
// [1] => 3
// )
//
// [T] => Array
// (
// [0] => 2
// [1] => 6
// )
//
// [R] => Array
// (
// [0] => 4
// )
//
// [C] => Array
// (
// [0] => 5
// )
//
// )
print_r($map['T']);
// Array
// (
// [0] => 2
// [1] => 6
// )
print_r($map['P']);
// Array
// (
// [0] => 1
// [1] => 3
// )
I have a multi-dimensional array and from where i want to choose 11 different words. Each word from different array index.
Here is the array link: My multi-dimensional array
array (
'w' =>
array (
0 => 'walls',
1 => 'well',
2 => 'why',
),
'e' =>
array (
0 => 'end',
),
'a' =>
array (
0 => 'advantage',
1 => 'afford',
2 => 'affronting',
3 => 'again',
4 => 'agreeable',
5 => 'ask',
6 => 'at',
),
'c' =>
array (
0 => 'children',
1 => 'civil',
2 => 'continual',
)
);
My Desire Output:
From w => well
From e => end
From a => again
and so on.
Output like: array(well, end, again, ...) as array.
Use the following code:
$f = array_keys($result); // grouping the indices, namely, the characters
$a = "";
for($c=0;$c<count($f);$c++){
$a .= $f[$c];
} // grouping the indices stored in array $f to a string, $a
$words = array();
for($c=0;$c<11;$c++){
$random = $a[rand(0,strlen($a)-1)];
$k = $result[$random];
// $k stores the array of the character index, stored in $result
$random2 = rand(0,count($k)-1);
$words[$c] = $k[$random2];
// choose a word from a given character array
$a = preg_replace("/".$random."/","",$a);
// remove the character from $a to prevent picking words which start with the same character
}
print_r($words);
I've tested and it was proved working
https://3v4l.org/qi1VP
You can achieve this usin array_rand() function :
PHP
$words = [];
$limit = 3; //Replace this with your limit, 11
$count = 0;
shuffle($array);
foreach($array as $key => $value) {
$words[] = $value[array_rand($value)];
$count++;
if ($limit == $count) {
break;
}
}
EvalIn
Check Online, and let me know.
using shuffle and array_slice you can get what you want.
A shuffle function makes your array random, and array slice slice 11 sub array from it.
Array slice takes 3 argument, first one is the array, second one is the offset from where you want to start and last one how much you need to cut.
$words = array();
shuffle($result);
$res = array_slice($result, 0, 11);
foreach($res as $key => $value){
shuffle($value);
$words[] = $value[0];
}
print_r($words);