I would like to present a list from 0 to 59 with the numbers 0 to 9 having a leading zero. This is my code, but it doesn't work so far. What is the solution?
for ($i=0; $i<60; $i++){
if ($i< 10){
sprintf("%0d",$i);
}
array_push($this->minutes, $i);
}
Using %02d is much shorter and will pad the string only when necessary:
for($i=0; $i<60; $i++){
array_push($this->minutes,sprintf("%02d",$i));
}
You are not assigning the result of sprintf to any variable.
Try
$padded = sprintf("%0d", $i);
array_push($this->minutes, $padded);
Note that sprintf does not do anything to $i. It just generates a string using $i but does not modify it.
EDIT: also, if you use %02d you do not need the if
Try this...
for ($i = 0; $i < 60; $i++) {
if ($i < 10) {
array_push($this->minutes, sprintf("%0d", $i));
}
array_push($this->minutes, $i);
}
You are ignoring the returned value of sprintf, instead of pushing it into your array...
important: The method you are using will result in some items in your array being strings, and some being integers. This might not matter, but might bite you on the arse if you are not expecting it...
Use str_pad:
for($i=0; $i<60; $i++){
str_pad($i, 2, "0", STR_PAD_LEFT)
}
I like the offered solutions, but I wanted to do it without deliberate for/foreach loops. So, here are three solutions (subtle variations):
Using array_map() with a designed callback function
$array = array_map(custom_sprintf, range(0,59));
//print_r($array);
function custom_sprintf($s) {
return sprintf("%02d", $s);
}
Using array_walk() with an inline create_function() call
$array = range(0,59);
array_walk($array, create_function('&$v', '$v = sprintf("%02d", $v);'));
// print_r($array);
Using array_map() and create_function() for a little code golf magic
$array = array_map(create_function('&$v', 'return sprintf("%02d", $v);'), range(0,59));
Related
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";
Let’s say I have the string http://www.example.com/images/[1-12].jpg. I would like to expand it into:
http://www.example.com/images/1.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
http://www.example.com/images/5.jpg
http://www.example.com/images/6.jpg
http://www.example.com/images/7.jpg
http://www.example.com/images/8.jpg
http://www.example.com/images/9.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/12.jpg
Here is my code:
$str = "http://www.example.com/images/[1-12].jpg";
while(preg_match_all("/^([^\\[\\]]*)\\[(\\d+)\\-(\\d+)\\](.*)$/m", $str, $mat)){
$arr = array();
$num = sizeof($mat[0]);
for($i = 0; $i < $num; $i++){
for($j = $mat[2][$i]; $j <= $mat[3][$i]; $j++){
$arr[] = rtrim($mat[1][$i].$j.$mat[4][$i]);
}
}
$str = implode(PHP_EOL, $arr);
}
It works fine even if I change $str to a more complex expression like the following:
$str = "http://www.example.com/images/[1-4]/[5-8]/[9-14].jpg";
But, unfortunately, zero-padded integers are not supported. So, if I begin with:
$str = "http://www.example.com/images/[001-004].jpg";
Expected result:
http://www.example.com/images/001.jpg
http://www.example.com/images/002.jpg
http://www.example.com/images/003.jpg
http://www.example.com/images/004.jpg
And the actual result:
http://www.example.com/images/001.jpg
http://www.example.com/images/2.jpg
http://www.example.com/images/3.jpg
http://www.example.com/images/4.jpg
How to change this behaviour so that my code produces the expected result? Also, what are the other shortcomings of my code? Should I really do it with the while loop and preg_match_all or are there faster alternatives?
UPDATE: Changing the seventh line of my code into
$arr[] = rtrim($mat[1][$i].str_pad($j, strlen($mat[2][$i]), 0, STR_PAD_LEFT).$mat[4][$i]);
seems to do the trick. Thanks a lot to sjagr for suggesting this. My question is still open because I would like to know the shortcomings of my code and faster alternatives (if any).
Per #SoumalyoBardhan's request, my suggestion/answer:
If you use str_pad(), you can force the padding based on the size of the matched string using strlen() found by your match. Your usage of it looks good to me:
$arr[] = rtrim($mat[1][$i].str_pad($j, strlen($mat[2][$i]), 0, STR_PAD_LEFT).$mat[4][$i]);
I really can't see what else could be improved with your code, although I don't exactly understand how preg_match_all would be used in a while statement.
A faster alternative with preg_split which also supports descending order (FROM > TO):
$str = "http://www.example.com/images/[12-01].jpg";
$spl = preg_split("/\\[([0-9]+)-([0-9]+)\\]/", $str, -1, 2);
$size = sizeof($spl);
$arr = array("");
for($i = 0; $i < $size; $i++){
$temp = array();
if($i%3 == 1){
$range = range($spl[$i], $spl[$i+1]);
$len = min(strlen($spl[$i]), strlen($spl[++$i]));
foreach($arr as $val){
foreach($range as $ran){
$temp[] = $val.str_pad($ran, $len, 0, 0);
}
}
}
else{
foreach($arr as $val){
$temp[] = $val.$spl[$i];
}
}
$arr = $temp;
}
$str = implode(PHP_EOL, $arr);
print($str);
It has the following result:
http://www.example.com/images/12.jpg
http://www.example.com/images/11.jpg
http://www.example.com/images/10.jpg
http://www.example.com/images/09.jpg
http://www.example.com/images/08.jpg
http://www.example.com/images/07.jpg
http://www.example.com/images/06.jpg
http://www.example.com/images/05.jpg
http://www.example.com/images/04.jpg
http://www.example.com/images/03.jpg
http://www.example.com/images/02.jpg
http://www.example.com/images/01.jpg
using php. I have the following number
4,564,454
454,454,454
54.54
65.43
I want to convert these into number for calculating. How can I do it? Right now, the type of these number is string.
Note: the comma is not a separate of a number, it is a notion to make a number nicer. I got this format from the ajax request, I cant change the format though. So, I have to use it.
Thanks
$var = floatval(str_replace(",", "", "454,454,454"));
$a='4,5,4';
$ab= explode(',', $a);
foreach ($ab as $b)
{
$sum+=$b; //perform your calculation
}
echo $sum;
First you need to remove ,(comma) from your string as below :
$str=str_replace(",", "", "454,454,454");
Then converting in numeric:
$int = (int)$str;
or
$int=intval($str);
now do your calculation using $int variable.
try this code
$str = '4,564,454';
$str2 = '454,454,454';
$str3= '54.54';
$str4= '65.43';
$sum=0;
$sum += array_sum(explode(',',$str));
$sum += array_sum(explode(',',$str2));
$sum += $str3;
$sum += $str4;
echo $sum;
I am getting deeper into PHP and I am attempting to double the original values of a given array in PHP. Here is the code if it were to return a different array:
$blandArray = array(1, 2, 3, 4);
function doubleNumbers($arr) {
$doubledArray = array();
for ($i=0; $i < count($arr); $i++) {
$doubledArray[$i] = $arr[$i] * 2;
}
return $doubledArray;
}
print_r(doubleNumbers($blandArray));
This returns the numbers doubled as expected, but in a new array. What I want is to double the original array. So, if blandArray was passed and echoed after running through the function, it would have the values doubled. I understand that I have to use the & to reference that in the argument passed, but I am having no luck. Any thoughts?
You have to not only pass by reference, but also change the variable!
function doubleNumbers(&$arr) {
for ($i=0; $i < count($arr); $i++) {
$arr[$i] *= 2;
}
}
$blandArray = array(1, 2, 3, 4);
doubleNumbers($blandArray);
print_r($blandArray);
Notice also that it doesn't return any more; that would also copy the array, so we just use it out-of-line.
As already mentioned, you pass by reference. This could also be achieved with array_map, such as:
$blandArray = array_map(function($val) {
return $val * 2;
}, $blandArray);
As far as im aware you would beable to just overwrite the old values . . .
$blandArray = array(1, 2, 3, 4);
function doubleNumbers($arr) {
for ($i=0; $i < count($arr); $i++) {
$arr[i] = $arr[i] * 2;
//or
$arr[i] *= 2;
}
}
print_r(doubleNumbers($blandArray));
I dont think you would have to return anything either if your always doubling the array into the same array you give the function. Im giving this answer from knowledge of Actionscript, the syntax maybe different hence why iv added 2 line within the loop.
I would like to serve an array of 25 elements randomly.
I'm not sure how to do this.
Say the array has numbers from 0 to 24.
I want to produce something like that:
5,4,6,7,8,9,10,20,21,22,23,24,25,1,2,11,14,15... etc
So if the generator outputs 23 it should not output it again
Thanks
$numbers = range(0, 24);
shuffle($numbers);
print_r($numbers);
Do you mean something like
$array;
$shuffledArray = shuffle($array);
In your concrete example you are talking about to output a comma separated string of numbers from 0 to 24
echo implode(',', shuffle(range(0,24));
for($i = 0; $i < 25; ++$i) {
$array[] = $i;
}
shuffle($array);
print_r($array);
The shuffle function is very useful in these cases.
<?php
$numbers = range(0, 24);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
http://php.net/manual/en/function.shuffle.php
$r = range(1,25);
shuffle($r);
var_dump($r);
If you have the array already, you can use the PHP function called shuffle():
http://php.net/manual/en/function.shuffle.php
if not, build the array like this:
<?php
$max = 24;
$num_array = array();
for($i=0;$i<=$max;$i++) $num_array[] = $i;
shuffle($num_array);
?>
Update: I've never seen the range function used before (by KingCrunch). Much better to use that one!