Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have one array
Array (
[1]=>123,456,789,3255
[2]=>585,478,437,1237
)
Search Text = 12
output I want -> 123,1237
What way should I go?
$array = array();
array_push($array,'1234',534,75,746);
array_push($array,'164',574,752,755);
array_push($array,'154',58,754,76);
$search_text = '75';
I want Output =
75,752,755,754
You can do this using strpos and a loop.
$numbers = array();
array_push($numbers,'1234', 534, 75, 746);
array_push($numbers,'164', 574, 752, 755);
array_push($numbers,'154', 58, 754, 76);
$searchNumber = '75';
$output = [];
foreach ($numbers as $number) {
if (strpos((string) $number, $searchNumber) !== false) {
$output[] = $number;
}
}
// 75, 752, 755, 754
echo implode(", ", $output);
If you are using PHP 8 you could even replace the strpos with str_contains function
if (str_contains($number, $searchNumber)) {
$output[] = $number;
}
RFC
str_contains
Try this:
$result = [];
$array = [];
$toSearch = '75';
array_push($array,'1234',534,75,746);
array_push($array,'164',574,752,755);
array_push($array,'154',58,754,76);
// If your array is one dimension
$result = array_filter($array, function($el) use ($toSearch) {
return strpos((string) $el, (string) $toSearch);
});
// For 2D array:
foreach ($array as $cur) {
$result = array_merge($result, array_filter($cur, function($el) use ($toSearch) {
return strpos((string) $el, (string) $toSearch);
}));
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to generate a number and save it in an array in RAM and then search for a match.
This is what my code should do:
-Generate a number
-Save it in a variable (array)
-Open a txt file and find a match from that array against the list of numbers in list.txt
-if found save it to Bingo.txt
<?php
function Fun()
{
$list = fopen("list.txt", "r");
$result = "BINGOOOOOO.txt";
//$command = "generatenumber.exe";
//$generatednumber = shell_exec($command);
$generatednumber = "1";
$matches = array();
if ($list) {
while ($getLine = fgets($list)) {
$getLine = rtrim($getLine); // remove newline
$source = $generatednumber;
var_dump($source);
if ($source) {
while ($buffer = fgets($source)) {
$buffer = rtrim($buffer);
if (in_array($getLine, explode(' ', $buffer)))
$matches[] = $buffer;
}
unset($source);
}
}
}
//show results:
print_r($matches);
$SaveResult = file_put_contents($matches, $result);
}
The issue now is that with number 1, bingo.txt file not created.
All sorts of issues in your code
An fgets() loop inside and fgets() loop will loose rows from your input
Move some of the code outside the loop, it sits better there
Get the function to return the results to you reather than outputting things itself.
function Fun($generatednumber)
{
$list = fopen("list.txt", "r");
//$command = "generatenumber.exe";
//$generatednumber = shell_exec($command);
$matches = array();
if ($list) {
while ($getLine = fgets($list)) {
$getLine = rtrim($getLine); // remove newline
if (in_array($generatednumber, explode(' ', $getLine))) {
$matches[] = $getLine;
}
}
}
return $matches;
}
$in = 1;
$matches = Fun($in);
$result = "BINGOOOOOO.txt";
$SaveResult = file_put_contents($result, $matches);
I have an array which contains bunch of strings, and I would like to find all of the possible combinations no matter how it's being sorted that match with given string/word.
$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];
input: stackoverflow
output:
#1 -> ['stack', 'over', 'flow']
#2 -> ['stackover', 'flow']
What I've tried is, I need to exclude the array's element which doesn't contain in an input string, then tried to match every single merged element with it but I'm not sure and get stuck with this. Can anyone help me to figure the way out of this? thank you in advance, here are my code so far
<?php
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$word = 'stackoverflow';
$dictHas = [];
foreach ($dict as $w) {
if (strpos($word, $w) !== false) {
$dictHas[] = $w;
}
}
$result = [];
foreach ($dictHas as $el) {
foreach ($dictHas as $wo) {
$merge = $el . $wo;
if ($merge == $word) {
} elseif ((strpos($word, $merge) !== false) {
}
}
}
print_r($result);
For problems like this you want to use backtracking
function splitString($string, $dict)
{
$result = [];
//if the string is already empty return empty array
if (empty($string)) {
return $result;
}
foreach ($dict as $idx => $term) {
if (strpos($string, $term) === 0) {
//if the term is at the start of string
//get the rest of string
$substr = substr($string, strlen($term));
//if all of string has been processed return only current term
if (empty($substr)) {
return [[$term]];
}
//get the dictionary without used term
$subDict = $dict;
unset($subDict[$idx]);
//get results of splitting the rest of string
$sub = splitString($substr, $subDict);
//merge them with current term
if (!empty($sub)) {
foreach ($sub as $subResult) {
$result[] = array_merge([$term], $subResult);
}
}
}
}
return $result;
}
$input = "stackoverflow";
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$output = splitString($input, $dict);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I was hoping someone could figure out why my code is not working for a 6-sided dice tallying the numbers for 6000 rolls using arrays.
<?php
// main //////////////////////////////////
//$throw_dice = array();
//$tally = array();
echo "debug - code runs to this point<br>\n";
$throw_dice = throw_dice($throw_dice);
$tally = tally_results($throw_dice);
echo "debug with tally: $tally[4]<br>\n";
exit;
$line = print_table($tally);
echo $line;
// functions ////////////////////////////////
function throw_dice ($f_throw_dice) {
/* required pseudocode:
for loop from 1 to 6000
populate each element with random number 1 - 6
end for loop
return array
*/
for ($i = 0; $i < 6000; $i++) {
$f_throw_dice[] = mt_rand(1,6);
}
return array($f_throw_dice);
}
function tally_results ($f_throw_dice) {
/*
use increment system example shown below with associative array:
$numbers = array(1, 2, 2, 1, 2, 1, 1, 1, 2)
foreach ($numbers as $number) {$tally[$number]++}
will give 5 for $tally[1] and 4 for $tally[2]
*/
//$tally = array('1' => 1,'2' => 2,'3' => 3,'4' => 4,'5' => 5,'6' => 6,);
//$numbers = array($f_throw_dice);
//$tally[0] = '1';
//$tally[1] = '2';
//$tally[2] = '3';
//$tally[3] = '4';
//$tally[4] = '5';
//$tally[5] = '6';
$tally = array();
foreach ($f_throw_dice as $number)
{
$tally[$number]++;
echo $tally;
}
}
function print_table($f_tally) {
/* required pseudocode:
note: concatenate entire formatted printout in one variable $line
Can start this way:
$line = "<pre>";
$line .= sprintf ("DIE #%10s", 'OCCURS');
$line .= "\n===============\n";
sort $f_tally by key
foreach loop
concatenate $line with another $f_tally element using the
sprintf format from last assignment
end loop
return $line
*/
$line = "<pre>";
$line .= sprintf ("DIE #%10s", 'OCCURS');
$line .= "\n===============\n";
ksort ($f_tally);
echo '<ul>';
foreach ($f_tally as $numbers => $tally) {
echo '<pre>',
$line .= sprintf('%s %s', $numbers, $tally), '</pre>';
// echo '<li>$numbers ($tally)</li>';
}
echo '</ul>';
}
?>
The result should look similar to this:
DIE # OCCURS
==============
1 1000
2 990
3 1038
4 1012
5 1007
6 953
A few issues.
1) In the throw_dice function, change:
return array($f_throw_dice);
...to:
return $f_throw_dice;
$f_throw_dice is already an array. So by wrapping it in an array function, you're adding an additional layer to your array, which causes the loop in the tally_results function to fail. So, just return $f_throw_dice as is.
2) And in the tally_results function, change:
foreach ($f_throw_dice as $number)
{
$tally[$number]++;
echo $tally;
}
...to:
foreach ($f_throw_dice as $number)
{
$tally[$number]++;
}
return $tally;
Here you're not returning $tally from the function, but rather are echoing it once for every loop over the dice results. Instead, wait 'til the loop is over then return it.
3) Then, in the print_table function, change:
echo '<ul>';
foreach ($f_tally as $numbers => $tally) {
echo '<pre>',
$line .= sprintf('%s %s', $numbers, $tally), '</pre>';
// echo '<li>$numbers ($tally)</li>';
}
echo '</ul>';
...to:
$line .= '<ul>';
foreach ($f_tally as $numbers => $tally) {
$line .= '<pre>';
$line .= sprintf('%s %s', $numbers, $tally) . '</pre>';
// echo '<li>$numbers ($tally)</li>';
}
$line .= '</ul>';
return $line;
And here you start building but then switch to echoing, and, again, you don't return anything from this function. So, instead of echoing the results, keep capturing them in the $line variable, then echo it at the end of the function.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how correctly make on php ?
If set range have small letters -> replace them on big.
length of string - const
number of symbols from 0
set range : [4,6]
Example :
17xG2v9Hj5 -> 17xG2V9Hj5
b7qfK5yte9 -> b7qfK5Yte9
My code :
$m = '17xG2v9Hj5';
$s1 = mb_substr($m, 0, 4); // -> 17xG
$s2 = mb_substr($m, 4, 3); // -> 2v9
$ss = ucwords(strtoupper($s2)); // -> 2V9
$s3 = mb_substr($m, 7,3); // -> Hj5
$my = $s1.$ss.$s3; // -> 17xG2V9Hj5
var_dump($m).'<br/>';
var_dump($s1).'<br/>';
var_dump($s2).'<br/>';
var_dump($ss).'<br/>';
var_dump($s3).'<br/>';
var_dump($my).'<br/>';// ??? ['<br/>'] for [var_dump()]
// don't work;
String : [a-z] and [0-9].
It is possible to make more shortly and faster?
Thanks.
I'm really not sure what you're trying to achieve?
var_dump is typically used for debug purposes, its output will be more readable if wrapped in <pre></pre> tags.
var_dump($my).'<br/>';
Will not actually append '<br/>' to the output of var_dump it will append it the the value returned by var_dump, in this case void
ie.
$out = var_dump($my).'<br/>'; //$out == '<br/>'
If you want to output <br/> after var_dump you must echo it separately.
ie.
var_dump($my);
echo '<br/>';
You may use substr_replace to do this in one round (Assuming range and string-length are fixed)
$in = '17xG2v9Hj5';
var_dump(substr_replace($in, mb_strtoupper(mb_substr($in, 4, 3)), 4, 3));
A multibyte variant of the substr_replace function can be found here
Answer below is based on Revision 1 of the question assuming a more general solution is wanted
Naive solution but should work if I understood your question correctly:
<?php
$in = '17xG2v9Hj5';
$range = [4,6];
var_dump(uc_range($in, $range));
function uc_range($string, array $range) {
if(!is_string($string)) {
throw new InvalidArgumentException('$string is supposed to be a string');
}
$chars = str_split_unicode($string);
foreach(range($range[0], $range[1]) as $keyIndex) {
if(isset($chars[$keyIndex])) {
$chars[$keyIndex] = mb_strtoupper($chars[$keyIndex]);
}
}
return implode("", $chars);
}
// see http://www.php.net/manual/en/function.str-split.php#107658
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
I have an array like this:
[0] = 2
[1] = 8
[2] = 7
[3] = 7
And I want to end up with an array that looks like:
[0] = 7
[1] = 7
Basically, remove all elements where they occur less than twice.
Is their a PHP function that can do this?
try this,
$ar1=array(2,3,4,7,7);
$ar2=array();
foreach (array_count_values($ar1) as $k => $v) {
if ($v > 1) {
for($i=0;$i<$v;$i++)
{
$ar2[] = $k;
}
}
}
print_r($ar2);
output
Array ( [0] => 7 [1] => 7 )
Something like this would work, although you could probably improve it with array_reduce and an anonymous function
<?php
$originalArray = array(2, 8, 7, 7);
foreach (array_count_values($originalArray) as $k => $v) {
if ($v < 2) {
$originalKey = array_search($k, $originalArray);
unset($originalArray[$originalKey]);
}
}
var_dump(array_values($originalArray));
$testData = array(2,8,7,7,5,6,6,6,9,1);
$newArray = array();
array_walk(
array_filter(
array_count_values($testData),
function ($value) {
return ($value > 1);
}
),
function($counter, $key) use (&$newArray) {
$newArray = array_merge($newArray,array_fill(0,$counter,$key));
}
);
var_dump($newArray);
Though it'll give a strict standards warning. To avoid that, you'd need an interim stage:
$testData = array(2,8,7,7,5,6,6,6,9,1);
$newArray = array();
$interim = array_filter(
array_count_values($testData),
function ($value) {
return ($value > 1);
}
);
array_walk(
$interim,
function($counter, $key) use (&$newArray) {
$newArray = array_merge($newArray,array_fill(0,$counter,$key));
}
);
var_dump($newArray);
You could use a combination of array_count_values (which will give you an associative array with the value as the key, and the times it occurs as the value), followed by a simple loop, as follows:
$frequency = array_count_values($yourArray);
foreach ($yourArray as $k => $v) {
if (!empty($frequency[$v]) && $frequency[$v] < 2) {
unset($yourArray[$k]);
}
}
I did not test it, but I reckon it works out of the box. Please note that you will loop over your results twice and not N^2 times, unlike an array_search method. This can be further improved, and this is left as an exercise for the reader.
This was actually harder to do than i thought...anyway...
$input = array(2, 8, 7, 7, 9, 9, 10, 10);
$output = array();
foreach(array_count_values($input) as $key => $value) {
if ($value > 1) $output = array_merge($output, array_fill(0, $value, $key));
}
var_dump($output);
$arrMultipleValues = array('2','3','5','7','7','8','2','9','11','4','2','5','6','1');
function array_not_unique($input)
{
$duplicatesValues = array();
foreach ($input as $k => $v)
{
if($v>1)
{
$arrayIndex=count($duplicatesValues);
array_push($duplicatesValues,array_fill($arrayIndex, $v, $k));
}
}
return $duplicatesValues;
}
$countMultipleValue = array_count_values($arrMultipleValues);
print_r(array_not_unique($countMultipleValue));
Is their [sic!] a PHP function that can do this?
No, PHP has no built-in function (yet) that can do this out of the box.
That means, if you are looking for a function that does this, it needs to be in PHP userland. I would like to quote a comment under your question which already suggest you how you can do that if you are looking for that instead:
array_count_values() followed by a filter with the count >1 followed by an array_fill() might work
By Mark Baker 5 mins ago
If this sounds a bit cryptic to you, those functions he names are actually built-in function in PHP, so I assume this comes most close to the no, but answer:
array_count_values()
array_fill()
This does the job, maybe not the most efficient way. I'm new to PHP myself :)
<?php
$element = array();
$element[0] = 2;
$element[1] = 8;
$element[2] = 7;
$element[3] = 7;
$count = array_count_values($element);
var_dump($element);
var_dump($count);
$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($count));
$result = array();
foreach ($it as $key=>$val){
if ($val >= 2){
for($i = 1; $i <= $val; $i++){
array_push($result,$key);
}
}
}
var_dump($result);
?>
EDIT: var_dump is just so you can see what's going on at each stage