I'm trying to figure out how to save results from the rand() function to 10 different files.
Here's my code:
<?php
for($i = 0; $i < 10; $i++)
{
$rand_valuec = rand(0,16);
echo "<b>Your Lucky Number is</b>: " . $rand_valuec . " <br />";
$fp = fopen("results.php", "w");
fwrite($fp, $rand_valuec);
fclose($fp);
}
Sample output:
Your Lucky Number is: 6
Your Lucky Number is: 16
Your Lucky Number is: 16
Your Lucky Number is: 8
Your Lucky Number is: 6
Your Lucky Number is: 10
Your Lucky Number is: 13
Your Lucky Number is: 5
Your Lucky Number is: 6
Your Lucky Number is: 5
results.php contains:
5
I need to save each result to a new file; e.g. 1result.php, 2result.php, 3result.php, 4result.php, ..., 10result.php. Any ideas? :-) Thanks!
You could just change your file open to read:
$fp = fopen($i."result.php", "w");
<?php
for($i=0; $i < 10; $i++)
{
$rand_valuec = rand(0,16);
echo "<b>Your Lucky Number is</b>: ".$rand_valuec." <br />";
$fp = fopen($i."results.php", "w");
fwrite($fp, $rand_valuec);
fclose($fp);
}
?>
try it:
<?php
$numberOfFiles = 10;
$numberOfLinesPerFile = 10;
$path = "/home/your-user/your-path/";
for ($fileIndex = 1; $fileIndex <= $numberOfFiles; $fileIndex++) {
$contentFile = "";
for ($i = 0; $i < $numberOfLinesPerFile; $i++) {
$rand_valuec = rand(0,16);
$content = "<b>Your Lucky Number is</b>: ".$rand_valuec." <br />";
}
file_put_contents($path . $fileIndex . "result.php", $content);
}
Related
I have a piece source code to search with Boolean retrieval
<?php
$path = "Korpus";
foreach(glob("$path/*.txt") as $file) {
foreach(file($file) as $line) {
echo $line."<br>";
}
}
$file = "";
$conv = "";
for($i = 1; $i < 4; $i++){
$file[$i] = file_get_contents("$path/Doc".$i.".txt");
$conv[$i] = explode(" ", strtolower($file[$i]));
echo "<br>";
print_r ($conv[$i]);
}echo "<br><br>";
?>
This is my Query
One AND Two AND NOT Three
I want the result like this
Term Doc1 Doc2 Doc3
One 1 0 0
Two 0 1 1
Three 0 1 0
Result : Doc1, Doc3
can someone help me to solve this problem ?
I'm trying to make a little PHP script for fun, and I'm a little stuck.
I want to divide an integer (for example 5) over multiple values.
For example:
$total = 5;
$mike = 0;
$ralf = 0;
$ashley = 0;
// Run the magic here
echo "Mike has " . $mike . " apples, Ralf has " . $ralf ." apples and Ashley has " . $ashley . " apples";
The output that I expect would look something like this:
Mike has 2 apples, Ralf has 1 apples and Ashley has 2 apples
Is there a way how to do this? :)
I can't do this hard coded, because I want the values to be randomized.
Cheers
Do it like this:
$total = 5;
$mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1)
$ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf
$ashley = $total - $mike - $ralf; // i hope you understand.
// use it.
Something like this would work:
$people = array('mike','ralf','ashley');
$num = count($people);
$sum = 5; // TOTAL SUM TO DIVIDE
$groups = array();
$group = 0;
while(array_sum($groups) != $sum) {
$groups[$group] = mt_rand(0, $sum/mt_rand(1,5));
if(++$group == $num){
$group = 0;
}
}
// COMBINE ARRAY KEYS WITH VALUES
$total = array_combine($people, $groups);
echo "Mike has " . $total['mike'] . " apples, Ralf has " . $total['ralf'] ." apples and Ashley has " . $total['ashley'] . " apples";
Solution is inspired from this answer: https://stackoverflow.com/a/7289357/1363190
Hope This function will do your work . it can work for variable # of persons also.
divide_items(10,['mike','ralf','ashley']);
function divide_items($total=1,array $persons){
$progressed = 0;
for($i=0;$i<count($persons);$i++){
echo $random_count = rand(1,$total);
if(($i==(count($persons)-1)) && $progressed<$total ){
$random_count1 =$total - $progressed;
echo $persons[$i]." has ".$random_count1 ." Items<br>";
continue;
}
$progressed = $progressed+$random_count;
if($progressed<=$total){
echo $persons[$i]." has ".$random_count ." Items<br>";
}else{
echo $persons[$i]." has 0 Item<br>";
}
$total = $total-$random_count;
$progressed = 0;
}
}
how to determine the sequence number of odd /even numbers using php ?
example ,i want output like here
odd numbers (1,3,5,7,9)
output
1 = 1
3 = 2
5 = 3
7 = 4
9 = 5
even numbers (2,4,6,8,10)
output
2=1
4=2
6=3
8=4
10=5
how code to make this function in php?
edit/update
if input 1 then output = 1 , if input 3 then output = 2, if input 21 then output= 11, etc,,
Try out this
php code
<?php
$result = '';
if(isset($_POST['value'])){
//assign POST variable to $num
$num = $_POST['value'];
$count = 0;
//for even numbers
if($num % 2 == 0){
$count = $num/2;
$result = "The Number ".$num." is Even on ".$count;
}else {
//if you know about sequences and series, you can understand it :P
$count = (($num-1) / 2)+1;
$result = "The Number ".$num." is Odd on ".$count;
}
}
?>
HTML COde
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="text" name="value"/>
<input type="submit" value="Check"/><br/>
<?php echo $result;?>
</form>
It is working correctly :P
<?php
$evenLimit = 10;
$oddLimit = 9;
$count = 1;
for ($x = 1; $x <= $oddLimit; $x = $x + 2) {
echo $x . "=" . $count . "<br>";
$count++;
}
echo "<br>";
$count = 1;
for ($x = 2; $x <= $evenLimit; $x = $x + 2) {
echo $x . "=" . $count . "<br>";
$count++;
}
?>
I am working on project which shows articles and this was done by article manager (a ready to use php script) but I have a problem, I want to show only four article titles and summaries from old list of article randomly which contains 10 article. Any idea how to achieve this process?
I have auto generated summary of article
<div class="a1">
<h3><a href={article_url}>{subject}</h3>
<p>{summary}<p></a>
</div>
When a new article is added the above code will generated and add into summary page. I want to add it to side of the main article page, where user can see only four article out of ten or more randomly.
<?php
$lines = file_get_contents('article_summary.html');
$input = array($lines);
$rand_keys = array_rand($input, 4);
echo $input[$rand_keys[0]] . "<br/>";
echo $input[$rand_keys[1]] . "<br/>";
echo $input[$rand_keys[2]] . "<br/>";
echo $input[$rand_keys[3]] . "<br/>";
?>
Thanks for your kindness.
Assuming I understood you correctly - a simple solution.
<?php
// Settings.
$articleSummariesLines = file('article_summary.html', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$showSummaries = 4;
// Check if given file is valid.
$validFile = ((count($articleSummariesLines) % 4 == 0) ? true : false);
if(!$validFile) {
die('Invalid file...');
}
// Count articles and check wether all those articles exist.
$countArticleSummaries = count($articleSummariesLines) / 4;
if($showSummaries > $countArticleSummaries) {
die('Can not display '. $showSummaries .' summaries. Only '. $countArticleSummaries .' available.');
}
// Generate random article indices.
$articleIndices = array();
while(true) {
if(count($articleIndices) < $showSummaries) {
$random = mt_rand(0, $countArticleSummaries - 1);
if(!in_array($random, $articleIndices)) {
$articleIndices[] = $random;
}
} else {
break;
}
}
// Display items.
for($i = 0; $i < $showSummaries; ++$i) {
$currentArticleId = $articleIndices[$i];
$content = '';
for($j = 0; $j < 4; ++$j) {
$content .= $articleSummariesLines[$currentArticleId * 4 + $j];
}
echo($content);
}
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 8 years ago.
Improve this question
I want to write a program to find the maximum gap between two 1s in a binary equivalent of a decimal number. For example for 100101: the gap is 2 and for 10101: the gap is 1.
<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);
$status = false;
$count = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
var_dump($binaryForm[$i]);
if($binaryForm[$i] == 1)
{
$status = false;
$count = 0;
}
else
{
$status = true;
$count += 1;
}
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>
but i was not successfull..
First use regex to find "0" groups, then sort by length, descending—take the first one in the list, and get it's length:
$numberGiven = 37;
$binaryForm = decbin($numberGiven);
// get all groups of "0", put list in $matches
preg_match_all('/(0+)/', $binaryForm, $matches_all);
$matches = $matches_all[0];
// sort descending
rsort($matches, SORT_STRING);
// get first `$matches[0]` and print string length
echo 'count = ' . strlen($matches[0]) . '<br>';
echo $binaryForm;
UPDATED: based on Mark Baker's comments below.
UPDATE #2: As brought up by afeijo in the comments below, the above does not exclude ending zeros. Here's a solution for that:
preg_match_all('/(0+)1/', $binaryForm, $matches_all);
$matches = $matches_all[1];
I would use the binary right-shift operator >> and iteratively shift by 1 bit and check if the current rightmost bit is a 1 until I've checked all the bits. If a 1 was found, the gap between the previous 1 is calculated:
foreach(array(5,17,25,1223243) as $number) {
$lastpos = -1;
$gap = -1; // means there are zero or excatly one '1's
// PHP_INT_SIZE contains the number of bytes an integer
// will consume on your system. The value * 8 is the number of bits.
for($pos=0; $pos < PHP_INT_SIZE * 8; $pos++) {
if(($number >> $pos) & 1) {
if($lastpos !== -1) {
$gap = max($gap, $pos - $lastpos -1);
}
$lastpos = $pos;
}
}
echo "$number " . decbin($number) . " ";
echo "max gap: {$gap}\n";
}
Output:
5 101 max gap: 1
17 10001 max gap: 3
25 11001 max gap: 2
1223243 100101010101001001011 max gap: 2
What you currently are doing is reseting the count each time you find a 1.
You need to keep track of the current max value:
$count = 0;
$maxCount = 0;
and where you set $count = 0 you should also do
if ($count > $maxCount)
$maxCount = $count;
$count = 0;
then
echo "count = " . $maxCount . "<br>";
In all:
<?php
$numberGiven = 251;
$binaryForm = decbin($numberGiven);
$status = false;
$count = 0;
$maxCount = 0;
for($i = 0; $i < strlen($binaryForm); $i++)
{
// Don't count leading zeroes.
if ($status == false && $binaryForm[$i] == 0) continue;
$status = true;
var_dump($binaryForm[$i]);
// We've found a 1. Remember the count.
if($binaryForm[$i] == 1)
{
if ($count > $maxCount)
$maxCount = $count;
$count = 0;
}
// We found a 0. Add one to count.
else
{
$count += 1;
}
}
echo "count = " . $count . "<br>";
echo $binaryForm;
?>
Disclaimer: Code not tested