how to iterate through string and get the second last number [closed] - php

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 need second last number from the list and the list can have varied length. I tried seperating it using explode(",", $layouts);
$layouts= '1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0';
Example : I need to get 30 from the string here.
please help

If this list can grow in size as you have indicated in the comment, then usually explode it into an array, then do a count of the size, subtract two from the total size and use that as an index to get the value:
//turn this to array
$layouts = '1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0';
$layoutsArray = explode(",", $layouts);
$xtarget = count($layoutsArray) - 2;
$xvalue = "";
if($xtarget > -1){
$xvalue = $layoutsArray[$xtarget];
}else {
//it could be wrong
}

You can explode it with , and get 2nd last value from array try the following code
$layouts= '1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0';
$array = explode(',',$layouts);
if(count($array) > 2){
$pair = array_slice($array, -2, 1, true);
$key = key($pair);
$value = current($pair);
echo $value;
}
Output
30

Related

Add two decimal values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
so I want to add two values (money values) but can't quite work it out.
I keep getting a notice, I've tried number_format to format it but even using that I get the 'Notice: A non well formed numeric value encountered'
$price = 0.00;
while($row = $result->fetch_assoc()) {
$dbprice = $row["ProductSellPrice"];
$price = $price + $dbprice;
//echo number_format($price + $dbprice,2);
}
however I get this problem: Notice: A non well formed numeric value encountered
If I add two values '5' + '1.5' I get '6' as a result.
Edit:
The values I were pulling from the database were formatted with commas.
PHP numbers uses dot as separator and seems that you have coma. Please replace the coma with the dot as first. After that you can cast the prices into floats and finally sum it up :)
You can try with this (based on you example):
<?php
$price = 0.00;
while($row = $result->fetch_assoc()) {
$dbprice = $row["ProductSellPrice"];
// Replace comma. Check also for possible thousand separator.
$dbprice = str_replace(',', '.', $dbprice);
$price = $price + (float)$dbprice;
//echo number_format($price + $dbprice, 2);
}
?>

How would I generate all possible line arrangements of an (x) word string over (y) lines in PHP? [closed]

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 4 years ago.
Improve this question
I am trying to write a function that takes the following 2 parameters:
A sentence as a string
A number of lines as an integer
So if I was to call formatLines("My name is Gary", 2); ...
The possible outcomes would be:
array("My name is", "Gary");
array("My name", "is Gary");
array("My", "name is Gary");
It would return: array("My name", "is Gary"); because the difference in character counts for each line is as small as possible.
So the part I am ultimately stuck on is creating an array of possible outcomes where the words are in the correct order, split over x lines. Once I have an array of possible outcomes I would be fine working out the best result.
So how would I go about generating all the possible combinations?
Regards
Joe
It seems like doing this by creating all possible ways of splitting the text and then determining the best one would be unnecessarily inefficient. You can count the characters and divide by the number of lines to find approximately the right number of characters per line.
function lineSplitChars($text, $lines) {
if (str_word_count($text) < $lines) {
throw new InvalidArgumentException('lines must be fewer than word count', 1);
}
$width = strlen($text) / $lines; // initial width calculation
while ($width > 0) {
$result = explode("\n", wordwrap($text, $width)); // generate result
// check for correct number of lines. return if correct, adjust width if not
$n = count($result);
if ($n == $lines) return $result;
if ($n > $lines) {
$width++;
} else {
$width--;
};
}
}
An answer has been accepted here - but this strikes me as a rather cumbersome method for solving the problem when PHP already provides a wordwrap() function which does most of the heavy lifting:
function format_lines($str, $lines)
{
$guess_length=(integer)(strlen($str)/($lines+1));
do {
$out=explode("\n", wordwrap($str, $guess_length));
$guess_length++;
} while ($guess_length<strlen($str) && count($out)>$lines);
return $out;
}
As it stands, it is rather a brute force method, and for very large inputs, a better solution would use optimum searching (adding/removing a larger initial interval then decreasing this in iterations)

Trying to get the most of the random element possibily from first 4 items in array php [closed]

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 5 years ago.
Improve this question
Hi am having 10 elements in array . Am trying to get my random element mostly from first 5 elements. Which means random element appearance from first 5 elements should be much greater than next 5 elements
$arr = array('a','b','c','d','e','f','g','h','i','j');
$random = $arr[array_rand($arr)];
Am using above one to get the random element normally
Use function rand(min_num, max_num):
function rand5($array) {
$part = rand(1, 10);
return ($part > 3) ? $array[rand(0, 4)] : $array[rand(5, 9)];
}
$arr = array('a','b','c','d','e','f','g','h','i','j');
$random = rand5($arr);
Try this simple and easy code :-
$arr = array('a','b','c','d','e','f','g','h','i','j');
$rand = rand(0,9);
echo $arr[($rand <= 6 ? ($rand%5) : $rand)];
You just have to get the random number between 0 to 9 and divide that number in 70%(0-6) and 30%(7-9). If its greater than 5 then only use the remainder else directly get that number
Here is the fiddle :- https://3v4l.org/TWGJJ

Multiply decimal number for price [closed]

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 5 years ago.
Improve this question
I'm a newbie in PHP, and for a woocommerce I'm trying to multiply a price by 2.
$priceOriginal = WC()->cart->get_cart_subtotal(); // return 450,00€
$priceNoCur = preg_replace( '/&.*?;/', '', $priceOriginal ); // return 450,00
$priceNoCurDot = preg_replace( '/,/', '.', $priceNoCur); // return 450.00
$priceFinalDot = floatval($priceNoCurDot) * 2;
echo $priceFinalDot; // return 0
I found how to delete de euro sign and change the coma by a dot, but when I multiply by two my result is 0 … why !?
SOLUTION
I find a other way to call the price : $priceOriginal = WC()->cart->total; then I was able to multiply this number as a normal calculation.
Your priceOriginal is not what telling, if I assume it is some thing like "450,00€" then I must return 900 when you multiple it by 2. try to var_dump($priceOriginal); before doing any further operation
$priceOriginal = "450,00€";
$priceNoCur = preg_replace( '/&.*?;/', '', $priceOriginal ); // return 450,00
$priceNoCurDot = preg_replace( '/,/', '.', $priceNoCur); // return 450.00
$priceFinalDot = floatval($priceNoCurDot) * 2;
echo $priceFinalDot; // returns 900
For debug:
$priceOriginal = WC()->cart->get_cart_subtotal();
var_dump($priceOriginal); //see what you get
As per your comment, If it is returning string(119) "450,00€",then you should trim your $priceOriginal variable like $priceOriginal = trim(WC()->cart->get_cart_subtotal()); before doing further operation because It may have some extra space characters.

Php sum numbers with the same string [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i try sum numbers with the same string , for get one only number to the end , for example this :
<?php
$result.="1";
$result.="4";
$result.="8";
$result.="346";
$end +=result;
echo $end;
?>
I try do this but no get never the result ok , only show all numbers but not the result of the sum , by this my question , i don´t know if i writte something bad or similar
Thank´s for the help , regards
You are concatenating instead of adding.
<?php
$result+=1; // Need the += here instead of .=
$result+=4;
$result+=8;
$result+=346;
$end +=result; // Like you already did here.
echo $end;
The problem is that you are trying to add up STRINGs not INTs. You have to convert the values.
$result+=intval("1");
$result+=intval("4");
$result+=intval("8");
$result+=intval("346");
$end =$result;
echo $end;
This is not how you are supposed to do it, if you really want to store every number, just use an array :
<?php
$myNumber = [];
$myNumber[] = 1;
$myNumber[] = 4;
$sum = 0;
foreach($myNumber as $r)
$sum += $r;
echo $sum;
?>
$sum will now contain the sum of every number. You could also use the array_sum function to perform this operation.

Categories