I have a array of say 50 elements. This array can be of size anything.
I want to have the first 10 elements of the array in a string.
I have the program as:
$array1= array("itself", "aith","Inside","Engineer","cooool","that","it","because");
$i=0;
for($f=0; $f < sizeof(array1); $f++)
{
$temparry = $temparry.array1[$f];
if(($f%10) == 0 && ($f !== 0))
{
$temparray[$i] = $temparray;
$i++;
}
}
==
so that at the end:
I get
temparray1= first 10 elements
temparray2 - next 10 elemnts...
I am not what I am missing in my loops.
After reading your comment, I think you want array_chunk [docs]:
$chunks = array_chunk($array1, 10);
This will create a multidimensional array with each element being an array containing 10 elements.
If you still want to join them to a string, you can use array_map [docs] and implode [docs]:
$strings = array_map('implode', $chunks);
This gives you an array of strings, where each element is the concatenation of a chunk.
This is something you can easily do with array_splice and implode.
Example:
<?php
$array = range(1, 50);
while ( $extracted = array_splice($array, 0, 10) )
{
// You could also assign this to a variable instead of outputting it.
echo implode(' ', $extracted);
}
all you are doing here is creating a temporary value and then deleting it. To save it into a string:
$myArray = array("itself", "aith","Inside","Engineer",
"cooool","that","it","because");
$myString = '';
for($i = 0; $i < 10; $i++) {
$myString .= $myArray[$i];
}
You could also run that inside of another for loop that would run through the entire array giving you ten-element increments.
Actually you can use arrray_slice and implode functions like this:
// put first 10 elements into array output
$output = array_slice($myArray, 10);
// implode the 10 elements into a string
$str = implode("", $output);
OP's fixed code as per comments below:
$array1= array("itself","aith","Inside","Engineer","cooool","that","it","because");
$temparry='';
$temparray = array();
for($f=0; $f < count($array1); $f++)
{
$temparry = $temparry.$array1[$f];
if(($f%3) == 0 && ($f !== 0))
{
$temparray[] = $temparry;
$temparry = '';
}
}
print_r($temparray);
Related
This question already has answers here:
Selecting multiple array elements
(3 answers)
Closed 1 year ago.
Hey GUys Im beginner to php programming here here i have 15 element in array . i want to display first 4 array element in first line and then second 4 array of element in nextline . i dont know how to achive it here is my code help me on this. thanks in advance
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
echo $nr_elm = count($arry); // gets number of elements in $arry
$nr_col = 4; // Sets the number of text Per Line
// If the array has elements
if ($nr_elm > 0)
{
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++)
{
echo $textInLine= $arry[$i]. ' | ';
// If the number of columns is completed for a line (rest of division of ($i + 1) to $nr_col is 0)
// Closes the current line, and begins another line
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $textInLine .= '/n'; }
}
}
echo $textInLine;
?>
Use array_chunk for this:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
foreach (array_chunk($array, $size) as $chunk) {
echo implode(' ', $chunk) . PHP_EOL;
}
Another solution without using array_chunk is using modulo:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
$counter = 0;
foreach ($array as $character) {
echo $character;
// echo new line after every 4th character, a space after the others
echo (++$counter % $size === 0) ? PHP_EOL : ' ';
}
Chunk the array and implode the items in the chunk.
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$chunks = array_chunk($array, 4);
foreach($chunks as $chunk){
echo implode(" ", $chunk) . "</br>\n";
}
Array_chunk splits the array in to pieces of the size you define.
The resulting array is multidimensional with the items in the subarray.
Implode takes the items in the subarray and adds the delimiter (" ") in between each item and makes it a string.
Use array_chunk, it will Split an array into chunks
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$arr = array_chunk($arry, 4, true);
foreach($arr as $value) {
echo implode(' ', $value) . PHP_EOL ;
}
?>
I don't know if the "15" is intentional, but if you want to remove it just remove the "echo".
I also recommend to use empty() to verify if your array is empty or not, just like this :
if (!empty($arry)) { //Code }
(notice the "!")
Now, for your main question what I would do is using a variable which increments up to 4, then you insert a line break with echo <br>; and reset the variable to 0.
The code should look something like this :
$c = 0;
for($i=0; $i<$nr_elm; $i++)
{
echo $arry[$i];
$c ++;
if ($c >= 4) {
echo "<br>";
$c = 0;
}
}
I hope this helped you
I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;
I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";
Given the following array:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
And assuming $n = 2, what is the most efficient way to get a count of each value in the array within $n of each value?
For example, 6 has 3 other values within $n: 5,7,7.
Ultimately I'd like a corresponding array with simply the counts within $n, like so:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
Is a simple foreach loop the way to go? CodePad Link
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);
My last answer was written without fully groking the problem...
Try sorting the array, before processing it, and leverage that when you run through it. This has a better runtime complexity.
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
asort($arr);
$n = 2;
$cnt = count($arr);
$counts = array_pad(array(), $cnt, 0);
for ($x=0; $x<$cnt; $x++) {
$low = $x - 1;
$lower_range_bound = $arr[$x]-$n;
while($low >= 0 && ($arr[$low] >= $lower_range_bound)) {
$counts[$x]++;
$low--;
}
$high = $x + 1;
$upper_range_bound = $arr[$x]+$n;
while($high < $cnt && $arr[$high] <= $upper_range_bound) {
$counts[$x]++;
$high++;
}
}
print_r($arr);
print_r($counts);
Play with it here: http://codepad.org/JXlZNCxW
I have a PHP array:
$arr = array(1,2,3,3,4,6,6);
I want to find the location of either duplicate in each duplicate pair (either 3 and either 6) and reset that value using rand(1,8). How would I go about doing this? I essentially need to make sure all of the array values are different.
You can try
$arr = array(1,2,3,3,4,6,6);
$dup = array_diff_assoc($arr,array_unique($arr));
$v = mt_rand(1, 8);
foreach ( $dup as $k ) {
while ( in_array($v, $arr) ) {
$v = mt_rand(1, 8);
}
$arr[$k] = $v;
}
echo "<pre>";
print_r($arr);
A simple way is to record how many items are in the array, use array_unique, and finally refill the array using a rand:
$size = count($arr);
$arr = array_unique($arr);
while (count($arr) < $size) {
$arr[] = rand(1,8,$arr);
}
You'd want to repeat this until count($arr) == count(array_unique($arr)). You could also make a random function that gives random values that are not already in the array pretty easily using in_array() and a loop.