For loops for array in PHP - php

How would I group 5 numbers in an array into each line? I've tried this code below but it results in something I'm not expecting it to be.
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
for ($i=0; $i<5; $i++)
{
echo ($result_data[$i]);
}
echo ("\n");
}
Result:
239298246244268
239298246244268
239298246244268
239298246244268
This loop keep repeating the first 5 numbers in my array. How do I make it to loop for every 5 numbers instead in my whole array of numbers? Thank you!

$x should be your index for the echo. Try this instead:
<?php
$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
for ($x = 0; $x < count($result_data); $x++)
{
echo ($result_data[$x]);
if(($x+1)%5==0)
{
echo ("\n");
}
}

use this $result_data[$x]
try this
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
if($x%5==0)
{
echo ("\n");
}
echo ($result_data[$x]);
}

Don't know much about your $result_data Array, but probably it should go like this:
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
for ($i=0; $i<5; $i++)
{
echo ($result_data[$x][$i]);
}
echo ("\n");
}

I think you want to do something like this
$i = 0;
foreach($result_data as $result) {
echo $result;
if($i < 5) {
echo ",";
} else {
echo "<br/>\n";
$i = 0;
}
$i++;
}

Something like this?
$chunks = array_chunk($result_data, 5);
foreach($chunks as $chunk) {
echo implode('', $chunk);
echo "\n";
}
See http://uk3.php.net/manual/en/function.array-chunk.php

Try this several line code:
$valuesDelimiter = ', ';
$lineDelimiter = "\n";
$input_array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$slited_array = array_chunk($input_array, 5);
array_walk($slited_array, function(&$arr) {$arr = implode($valuesDelimiter, $arr);});
$result = implode($lineDelimiter, $slited_array);

Related

Why can't I use a function to simplify my "for loops"

I build a webpage to crack simple MD5 hash of a four digit pin for fun. The method I used was basically try all combination and check against the MD5 value the user has entered. Below is the PHP code I created to accomplish the goal.
Debug Output:
<?php
$answer = "PIN not found";
if (isset($_GET['md5'])) {
$txt = 'abcdefjhig';
$time_pre = microtime(TRUE);
$value = $_GET['md5'];
$show = 15;
for ($i = 0; $i <= 9; $i++) {
$first = $i;
for ($j = 0; $j <= 9; $j++) {
$second = $j;
for ($k = 0; $k <= 9; $k++) {
$third = $k;
for ($x = 0; $x <= 9; $x++) {
$fourth = $x;
$whole = $first . $second . $third . $fourth;
$check = hash('md5', $whole);
if ($check == $value) {
$answer = $whole;
echo "The pin is $answer";
}
if ($show > 0) {
print"$check $whole \n";
$show = $show - 1;
}
}
}
}
}
echo "\n";
$time_post = microtime(TRUE);
print "Elapsed time:";
print $time_post - $time_pre;
}
?>
Notice that in the middle there are four very similar for loops,I tried to simplify this by using functions, but it just returns one four digit number which is 9999 instead of all of them.
Below is the function I created:
function construct($input){
for($i=0; $i<=9, $i++){
$input=$i;
}
return $input
}
Then I tried to call this function for four times to form all of the four digit numbers but it just gives me 9999. Can anybody help? Thanks a lot.
Try this:
for ($i=0; $i<=9999 ; $i++) {
$whole = sprintf('%04d', $i);
$check=hash('md5', $whole);
if($check==$value){
$answer=$whole;
echo "The pin is $answer";
break; //remove this if you do not want to break the loop here
}
if ($show>0) {
print"$check $whole \n";
$show=$show-1;
}
}
You're using numbers from 0 to 9999, so why just loop through those numbers? You can add zero's by using str_pad() like so:
for ($i = 0; $i <= 9999; $i++) {
$whole = str_pad($i, 4, '0', STR_PAD_LEFT);
}
Also I'd like to mention that you really should think about better formatting of your code, especially indentation

How should I suppose to print $headcount alone in the following statement? Suggest any pre-defined functuions too

I flip a coin until I get three heads in a row!
<?php
$headcount = 0;
$flipcount = 0;
while ($headcount < 3) {
$flip = rand(0, 1);
$flipcount++;
if($flip) {
$headcount++;
echo "H<br>";
}
elseif ($headcount > 3) {
$count_head = $headcount;
for($i = 0; $i < $headcount; $i++) {
$count_head = $i;
}}
else {
$headcount = 0;
echo "T<br>";
}
}
echo "<p>It took {$flipcount} flips!</p>";
echo "<p>It took {$count_head} flips!</p>";
?>
Use two variables that you increment when the roll is heads. One is the count of sequential heads, which gets set back to 0 when you roll tails, the other is the count of all heads, which doesn't get reset.
<?php
$headcount = 0;
$allheads = 0;
$flipcount = 0;
while ($headcount < 3) {
$flip = rand(0, 1);
$flipcount++;
if($flip) {
$headcount++;
$allheads++;
echo "H<br>";
}
else {
$headcount = 0;
echo "T<br>";
}
}
echo "<p>It took {$flipcount} flips!</p>";
echo "<p>There were {$allheads} heads!</p>";
?>
DEMO

How to count how many duplicates an array has in Php

I'm new to Php and today I came across the rand()-function. I'd like to fill an array with numbers created with this function and then count the number of its duplicates. I already tried it a first time, but somehow I seem to be on the woodway.
<?php
$numbers = array();
for ($i=0; $i < 100; $i++) {
$numbers[$i] = rand(0, 100);
}
//$numbers = array(12,12,12,12);
echo "random numbers generated.<br>";
$arrLength = count($numbers);
$arrWithDoubles = array();
for ($i=0; $i < $arrLength; $i++) {
//echo "start looping for i: ".$i."! numbers['i'] has the content".$numbers[$i].".<br>";
for ($x=$i; $x < $arrLength; $x++) {
//echo "looped for x: ".$x."! numbers['x'] has the content".$numbers[$x].".<br>";
if($numbers[$i] == $numbers[$x]) {
if($i != $x) {
//echo "pushed to 'arrWithDoubles'.<br>";
array_push($arrWithDoubles, $numbers[$x]);
}
}
}
}
echo "numbers of doubles: ".count($arrWithDoubles)."<br>";
echo "list of numbers which were double:<br>";
for ($i=0; $i < count($arrWithDoubles); $i++) {
echo $arrWithDoubles[$i];
echo "<br>";
}
?>
The array_unique() function removes duplicates from an array, then just add a bit of math.
<?php
$numberOfDuplicates = count($orginalArray) - (count($orginalArray) - count(array_unique($originalArray)));
?>
$origin = array(2,4,5,4,6,2);
$count_origin = count($origin);
$unique = array_unique($origin);
$count_unique = count($unique);
$duplicates = $count_origin - $count_unique;
echo $duplicates;
$count = array();
foreach ($srcRandom as $sr) {
if (!array_key_exists ($sr, $count) ) {
$count[$sr] = 1;
continue;
}
$count[$sr]++;
}
var_dump ($count);
Thanks for all your input. With that I came to the following solution which fits my demand the best:
<?php
function countValueInArray($value, $array) {
$count = 0;
for ($i=0; $i < count($array); $i++) {
if($value == $array[$i]) {
$count++;
}
}
return $count;
}
$numbers = array();
for ($i=0; $i < 100; $i++) {
$numbers[$i] = rand(0, 100);
}
$duplicates = array();
for ($x=0; $x < count($numbers); $x++) {
$number = countValueInArray($numbers[$x], $numbers);
if ($number > 1) {
array_push($duplicates, $numbers[$x]);
}
}
$duplicatesList = array_values(array_unique($duplicates));
echo "number of duplicates: ".count($duplicatesList);
echo "<br>these are: <br>";
print_r($duplicatesList);
?>
Thanks a lot for your help!

PHP Array, Get every 4 results and output in a loop

I'm trying to output my array results in groups of 4.
<?php for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } ?>
The above does 4, but obviously doesn't re-loop.
You can loop whole array and group you output with help of "%" operator.
<div>
<?php for ($i = 0; $i < count($array); $i++) {
if (($i % 4) == 0) {
echo "</div><div>";
}
echo "Element " . $array[$i]; // CODE
}
</div>
Other than using Mod as the other answers show, you could use array_chunk() to create the groups:
$groups = array_chunk($original_array, 4);
foreach($groups as $group){
echo '<div>';
foreach($group as $item){
echo $item;
}
echo '</div>';
}
You can use a while loop to reloop for the whole results to be printed
<?php while(conditions) {
for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } } ?>
Try this that way you can jump by 4
for ($i = 0; $i < 20; $i = $i+4) {
echo $i.'<br/>';
}
I would use a foreach and then just throw in an extra check to output the divs.
$i=0;
foreach ($array as $key->$val)
{
if($i%3==0)
{
echo "<div>";
}
// your stuff
if($i%3==0)
{
echo "</div>";
}
$i++;
}
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
you can check out from here http://php.net/manual/en/function.array-slice.php
try this, use nested for loop, this will loop 4 times. You can try to integrate with your code. If
for ($i = 0; $i < 4; $i++){
for($j = 0; $j < 4; $j++){
echo $a[$j++];
}
echo "<br/>";
}
I hope it can help you.
you can try $i++, because you use ++$i in this way "for" works 3 times!
for ($i = 0; $i < 4; $i++)

add in loop in multi dimensional array

i am facing a problem
can some one suggest me
for ($i = 1; $i <= 2; $i++) {
$r2 = 0;
for ($t = 1; $t <= 2; $t++) {
echo $r2;
$r2++
}
}
output is 0101;
can i get output 0123 ??? please
if
for ($i = 1; $i <= 3; $i++) {
$r2 = 0;
for ($t = 1; $t <= 3; $t++) {
echo $r2;
$r2++
}
}
output is 010101;
can output 012345678 ??? please
and if
for ($i = 1; $i <= 4; $i++) {
$r2 = 0;
for ($t = 1; $t <= 4; $t++) {
echo $r2;
$r2++
}
}
output is 01010101;
can output 0123456789101112131415 ??? please
i think you understand
thanks
In all of these cases you are initializing $r2=0; in the inner loop. It should be outside the loop.
$r2=0;
for($i=1;$i<=2;$i++){
for($t=1;$t<=2;$t++){
echo $r2;
$r2++
}
}
This would produce "1234".
why are you using two nested for loops ?
why not just use one:
for ($i=0; $i<=15; $i++) echo $i . " ";
Try this:
$r2 = 10;
for($t = 0; $t <= $r2; $t++){
echo $r2;
}
Oh wait.. I get it now, why you have the two nested loops, you want to essentially raise a number to the power of 2 in order to control the number of values output. In that case, what you want is simply this:
// this is the variable you need to change to affect the number of values outputed
$n = 2;
// Square $n
$m = $n * $n;
// Loop $m times
for ($i = 0; $i < $m; $i++) {
echo $i;
}

Categories