Working around for loop [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have noticed similar repetition and trying to work around using a single for loop for this if I can to minimize the code length:
I wouldn't need to use a switch case if I can form a loop instead?
$returnNo variable starts at 5, each case multiplied by 2 then minus 1.
where it shows "$a<=", it starts at 5 and each case multiplied by 2 then plus 3.
the if() statement starting at if($matchno == 7), each case multiplied by 2 then plus 1.
the final if() statement starting at if($matchno == 8), each case multiplied by 2.
I have done up to case 64, it will actually go up to 512. As I know the code is repeating I am hoping someone can help me produce a single loop for this?
Many thanks!
switch($max) {
case 80 :
$returnNO = 5;
for($a = 1; $a<=5; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 7){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 8){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 160 :
$returnNO = 9;
for($a = 1; $a<=13; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 15){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 16){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 320 :
$returnNO = 17;
for($a = 1; $a<=29; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 31){
$matchinfo['winner'] = true;
return $matchinfo;
} elseif($matchno == 32){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 640 :
$returnNO = 33;
for($a = 1; $a<=61; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 63){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 64){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
}
}

I'll use the first two cases as an example:
switch ($max) {
case 80:
$returnNO = 5;
$loopCount = 5;
$winner = 7;
$thirdWinner = 8;
break;
case 160:
$returnNO = 9;
$loopCount = 13;
$winner = 15;
$thirdWinner = 16;
break;
...
}
for ($a = 1; $a <= $loopCount; $a++) {
if ($matchno == $a || $matchno == ($a + 1)) {
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
}
if ($matchno == $winner) {
$matchinfo['winner'] = true;
return $matchinfo;
} else if ($matchno == $thirdWinner) {
$matchinfo['third_winner'] = true;
return $matchinfo;
}
Simply explained, remove the code that repeats all the time and try to parameterize it (either by creating a function or by putting all repeated code somewhere else... in this example, I put the repeating code after the switch statement and paremeterized it.

If I understood well, here is an alternative solution which I think would work for all cases you specified, with no use of switch case.
$div10 = $max / 10;
$maxLoop = $div10 - 3;
$returnNO = $div10 / 2 + 1;
for($a = 1; $a<=$maxLoop; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == ($div10-1)){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == $div10){
$matchinfo['third_winner'] = true;
return $matchinfo;
}

Related

How to do addition between two dropdown menus containing 1-5?

This is the code I have so far. I'm trying to use two dropdown menus in my HTML form that contains a 1-5 each and simply add them using POST.
//action for dropdown menu addition
$dropdownValueA = $_POST["dropdown1"];
$dropdownValueB = $_POST["dropdown2"];
$valueone = 0;
$valuetwo = 0;
if ($dropdownValueA == "1a"){
$valueone = 1;
}
if ($dropdownValueA == "2a"){
$valueone = 2;
}
if ($dropdownValueA == "3a"){
$valueone = 3;
}
if ($dropdownValueA == "4a"){
$valueone = 4;
}
if ($dropdownValueA == "5a"){
$valueone = 5;
}
if ($dropdownValueB == "1b"){
$valuetwo = 1;
}
if ($dropdownValueB == "2b"){
$valuetwo = 2;
}
if ($dropdownValueB == "3b"){
$valuetwo = 3;
}
if ($dropdownValueB == "4b"){
$valuetwo = 4;
}
if ($dropdownValueB == "5b"){
$valuetwo = 5;
}
echo $valueone + $valuetwo;
It's totally not clear what is your problem and what is not works as expected. But your code is... not good :) Maybe try something like
if( preg_match('/^([1-5])a$/', $dropdownValueA, $m) ) {
$valueone = $m[1];
}
if( preg_match('/^([1-5])b$/', $dropdownValueA, $m) ) {
$valuetwo = $m[1];
}
echo (int)$valueone + (int)$valuetwo;
If the numbers will always come first, this will be your best option.
$dropdownValueA = $_POST["dropdown1"];
$dropdownValueB = $_POST["dropdown2"];
$valueone = intval($dropdownValueA);
$valuetwo = intval($dropdownValueB);
echo $valueone + $valuetwo;
3v4l HERE

How do I query incomplete input

I want to transform query string like pending, shipped or cancel to number status.
$q = strtolower($keyword);
if($q == 'pen' or $q == 'pend' or $q == 'pending' ) {
$d = 1;
} elseif($q == 'shi' or $q == 'ship' or $q == 'shipped') {
$d = 2;
} elseif($q == 'can' or $q == 'cancel' ) {
$d = 3;
} else {
$d = 4;
}
$query->whereStatus($d);
Current query working fine but too much or. It's possible to do in shorten way?
str_is(query, stringToSearch) will probably be enough:
if (str_is('pen*', $q)) {
$d = 1;
}
Else you could parse them from arrays:
$pendingArray = ['pen', 'pend', 'pending'];
if (in_array($q, $pendingArray)) {
$d = 1;
}
If these are all the conditions you need, you could always use a switch.
$q = strtolower($keyword);
$d = 4;
switch($q) {
case 'pen':
case 'pend':
case 'pending':
case 'pen':
$d = 1;
break;
case 'shi':
case 'ship':
case 'shipped':
$d = 2;
break;
case 'can':
case 'cancel':
$d = 3;
break;
}
$query->whereStatus($d);
If this needs to be called on a model, it could be saved to a Laravel scope function like so:
on Laravel model
public function scopeSearchStatus($query, $keyword) {
/** All the code above **/
}
Then it can be called cleanly anywhere you'd like:
SomeModel::searchStatus($keyword);
You could also try this:
<?php
$q = strtolower($keyword);
$d = (preg_match('/\b(pen|pend|pending)\b/', $q)) ? 1 : 4;
$d = (preg_match('/\b(shi|ship|shipped)\b/', $q)) ? 2 : 4;
$d = (preg_match('/\b(can|cancel|)\b/', $q)) ? 3 : 4;
$query->whereStatus($d);

PHP Switch case & if statement not returning correct values

I'm kind of new to PHP and I'm trying to write a script that counts points after a user inputs values.
Here's the code:
<?php
$pla = $_GET['players'];
$plu = $_GET['plugins'];
$type = $_GET['type'];
$location = $_GET['location'];
totalPoints();
function typePoints($type) { //Returns points depending on server type
switch (strtolower($type)) { //Switch the type of server between all types and see how many points to return :)
case "standard minecraft": return 1;
break;
case "snapshot": return 2;
break;
case "craftbukkit": return 2;
break;
case "bungeecord": return 1;
break;
case "spigot": return 2;
break;
case "paperspigot": return 2;
break;
case "feed the beast": return 3;
break;
case "technic": return 3;
break;
case "pixelmon": return 3;
break;
default: echo 'Incorrect Server Type!';
exit;
break;
}
}
function playerPoints($players) { //Returns points depending on amount o players
if ($players >= 2 && $players <= 5) {
return 2;
} elseif ($players >= 6 && $players <= 10) {
return 4;
} //Between 6-10, return 4 points... AND SO ON...
elseif ($players >= 11 && $players <= 16) {
return 8;
} elseif ($players >= 17 && $players <= 25) {
return 12;
} elseif ($players >= 26 && $players <= 30) {
return 16;
} elseif ($players >= 31 && $players <= 36) {
return 18;
} elseif ($players >= 37 && $players <= 45) {
return 20;
} elseif ($players >= 46 && $players <= 50) {
return 22;
} elseif ($players >= 51 && $players <= 56) {
return 24;
} elseif ($players >= 57 && $players <= 65) {
return 26;
} elseif ($players >= 66 && $players <= 70) {
return 28;
} elseif ($players >= 71 && $players <= 76) {
return 30;
} elseif ($players >= 77 && $players <= 85) {
return 32;
} elseif ($players >= 86 && $players <= 90) {
return 34;
} elseif ($players >= 91 && $players <= 96) {
return 36;
} elseif ($players >= 97 && $players <= 105) {
return 38;
} elseif ($players >= 106 && $players <= 110) {
return 40;
} elseif ($players > 110) {
return 44;
}
}
function pluginPoints($plugins) {
if ($plugins == 0) {
return 0;
} elseif ($plugins >= 1 && $plugins <= 3) {
return 2;
} //Between 1-3, return 2 points.... AND SO ON...
elseif ($plugins >= 4 && $plugins <= 15) {
return 6;
} elseif ($plugins >= 16 && $plugins <= 30) {
return 10;
} elseif ($plugins >= 31 && $plugins <= 40) {
return 14;
} elseif ($plugins >= 41 && $plugins <= 50) {
return 20;
} elseif ($plugins > 50) {
return 24;
}
}
function locationPoints($location) {
switch (strtolower($location)) { //Switch between locations, easy to add a new one later in the future. :)
case "montreal": return 1;
break;
case "france": return 1;
break;
default: echo "Incorrect Location!";
exit;
break;
}
}
function totalPoints() { //Call this function to get the amount of points finally.
$totalPoints = typePoints($type) + playerPoints($pla) + pluginPoints($plu) + locationPoints($location);
echo 'Total points: ' . $totalPoints;
}
?>
The problem is the switch statement in function typePoints($type) always returns the default: echo 'Incorrect Server Type!'; exit; break;.
Also, function playerPoints($players) returns 0 even though I put in a number like 37.
I used this:
http://website.com/planpicker.php?players=121&location=france&plugins=80&type=technic
Can anyone tell me why?
This is not a duplicate question, the "marked duplicate" talks about different files, but this is within the same file.
The 4 variables are not accessible from totalPoints function. You should pass those parameters to function. You should call function as :
totalPoints($type,$pla,$plu,$location);
And define the function as
function totalPoints($type,$pla,$plu,$location)
It's because you call your functions in another function without passing the values in parameter.
The totalPoints function is not aware of the value of $type or $pla for example as they are not GLOBALS.
You have to pass the variables to the function you want to call :
function totalPoints($type, $pla, $plu, $location) //Call this function to get the amount of points finally.
{
$totalPoints = typePoints($type) + playerPoints($pla) + pluginPoints($plu) + locationPoints($location);
echo 'Total points: '.$totalPoints;
}
And then call the function like this :
totalPoints($type,$pla,$plu,$location);
The variables that were decared outside of the functions need to be made accessible to the totalPoints function. The easiest way is to use global
function totalPoints() {
global $pla;
global $plu;
global $type;
global $location;
$totalPoints = typePoints($type) + playerPoints($pla) + pluginPoints($plu) + locationPoints($location);
echo 'Total points: '.$totalPoints;
}

automatic number increase in php based web form [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 7 years ago.
Improve this question
So I have created an html form which then posts the results to a php file that overlays them on a PDF and then emails that PDF to myself and the email that was put in the form. All I want to do now is find a simple way to make it so that the PDF includes a sequential number.
For example: When the form is filled out for the first time the number 0001 is input automatically into the PDF and 0002 for the second time and so on.
Is there an easy PHP function to accomplish this?
Essentially I am creating an online invoicing form so when I do service calls I can create an invoice on the spot from a web browser which is then emailed to my office and the client.
Any help would be greatly appreciated.
For an incrementing number, you could keep a number in a database and then extract it, add 1 to it, use it, and then put it back in the DB for next time, but this seems complicated. Somebody in the comments mentioned using the timestamp, which would be done like so:
$invoicenumber = time(); //This number will always be unique
The time function works like so (copied from w3schools):
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Since actual seconds can only go up (increment), this number will never be the same twice.
I hope this is helpful.
-Edit
You can also display this date/time in a readable format like so:
$time = time();
echo date("Y-m-d H:i:s",$time);
-Edit 2
If you want an incrementing number, you basically need a very simple database to save it, which might be as simple as a table called invoices, with a column called invoicenumber, which stores your invoice number in it. You could / probably should use this to store other invoice information in it too, so you'd have each invoice number saved (which means we want to only get the highest one)
Then your code would look like this, for each time you want to use it:
Firstly you'd have a database information file (settings.php or something similar) with your database definitions in it, which might look like this:
define('DB_HOST', 'localhost');
define('DB_USER', 'db_username');
define('DB_PASS', 'db_password');
define('DB_NAME', 'database_name');
Your code would look like this:
//Establish a mysql connection
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Set up a query to get the highest number
$query = "SELECT invoicenumber FROM invoices ORDER BY invoicenumber DESC LIMIT 1";
//Get the result
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
//If we have a record
if($row){
//New invoice number
$invoicenumber = $row['invoicenumber']++;
//Else (database is empty, so start at the beginning)
}else{
$invoicenumber = 1;
}
//Now we have our invoice number, so do whatever you want with it
/**
* Code here to use the number
* */
//Now we wanna add the new invoice to the database, so
/**
* Add any other info to this statement if you want.
* If any of it is user submitted data, be sure to use prepared statements
* (just look at php.net's documentation on prepared statements)
* w3schools also has some nice tutorials on how to safely insert stuff
* in to a database, so check it all out :)
* */
$query = "INSERT INTO invoices(invoicenumber) VALUES($invoicenumber)";
//Execute the query
if($mysqli->query($query)){
//Show success
echo "Invoice $invoicenumber has been added to the database.";
}else{
//Show error
echo "Unfortunately we could not add invoice $invoicenumber to the database.";
}
//Now we can clear up our resources
$stmt->free_result(); $stmt->close(); $mysqli->close();
Please note: this is a very basic example. Yours will have additions and enhanced security if you are using user submitted data, so please do your homework and make sure that you fully understand each line of this code before you proceed to use it.
I do exactly the same with patient accession numbers on patient reports.
include('/home/user/php/class.pdf2text.php');
$p2t = new PDF2Text();
$p2t->setFilename($pdf);
$p2t->decodePDF();
$data = $p2t->output();
$len = strlen($data);
$pos = strpos($data,$accession);
if (pos){
$in .= "$accession,";
$checked++;
}
else{
$missingPDF += 1;echo "\n<p> <span class='bold red'>INCORRECT ACCESSION NUMBER c=$row[0] p=$row[1]</span>\n";
}
if ($checked > 0){
$in = substr($in,0,-1) . ')';
$sql = "UPDATE `Patient` SET `PDF`=1 WHERE $in";
}
pdf2text.php
class PDF2Text {
// Some settings
var $multibyte = 4; // Use setUnicode(TRUE|FALSE)
var $convertquotes = ENT_QUOTES; // ENT_COMPAT (double-quotes), ENT_QUOTES (Both), ENT_NOQUOTES (None)
var $showprogress = true; // TRUE if you have problems with time-out
// Variables
var $filename = '';
var $decodedtext = '';
function setFilename($filename) {
// Reset
$this->decodedtext = '';
$this->filename = $filename;
}
function output($echo = false) {
if($echo) echo $this->decodedtext;
else return $this->decodedtext;
}
function setUnicode($input) {
// 4 for unicode. But 2 should work in most cases just fine
if($input == true) $this->multibyte = 4;
else $this->multibyte = 2;
}
function decodePDF() {
// Read the data from pdf file
$infile = #file_get_contents($this->filename, FILE_BINARY);
if (empty($infile))
return "";
// Get all text data.
$transformations = array();
$texts = array();
// Get the list of all objects.
preg_match_all("#obj[\n|\r](.*)endobj[\n|\r]#ismU", $infile . "endobj\r", $objects);
$objects = #$objects[1];
// Select objects with streams.
for ($i = 0; $i < count($objects); $i++) {
$currentObject = $objects[$i];
// Prevent time-out
#set_time_limit ();
if($this->showprogress) {
// echo ". ";
flush(); ob_flush();
}
// Check if an object includes data stream.
if (preg_match("#stream[\n|\r](.*)endstream[\n|\r]#ismU", $currentObject . "endstream\r", $stream )) {
$stream = ltrim($stream[1]);
// Check object parameters and look for text data.
$options = $this->getObjectOptions($currentObject);
if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"])) )
// if ( $options["Image"] && $options["Subtype"] )
// if (!(empty($options["Length1"]) && empty($options["Subtype"])) )
continue;
// Hack, length doesnt always seem to be correct
unset($options["Length"]);
// So, we have text data. Decode it.
$data = $this->getDecodedStream($stream, $options);
if (strlen($data)) {
if (preg_match_all("#BT[\n|\r](.*)ET[\n|\r]#ismU", $data . "ET\r", $textContainers)) {
$textContainers = #$textContainers[1];
$this->getDirtyTexts($texts, $textContainers);
} else
$this->getCharTransformations($transformations, $data);
}
}
}
// Analyze text blocks taking into account character transformations and return results.
$this->decodedtext = $this->getTextUsingTransformations($texts, $transformations);
}
function decodeAsciiHex($input) {
$output = "";
$isOdd = true;
$isComment = false;
for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
switch($c) {
case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
case '%':
$isComment = true;
break;
default:
$code = hexdec($c);
if($code === 0 && $c != '0')
return "";
if($isOdd)
$codeHigh = $code;
else
$output .= chr($codeHigh * 16 + $code);
$isOdd = !$isOdd;
break;
}
}
if($input[$i] != '>')
return "";
if($isOdd)
$output .= chr($codeHigh * 16);
return $output;
}
function decodeAscii85($input) {
$output = "";
$isComment = false;
$ords = array();
for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ')
continue;
if ($c == '%') {
$isComment = true;
continue;
}
if ($c == 'z' && $state === 0) {
$output .= str_repeat(chr(0), 4);
continue;
}
if ($c < '!' || $c > 'u')
return "";
$code = ord($input[$i]) & 0xff;
$ords[$state++] = $code - ord('!');
if ($state == 5) {
$state = 0;
for ($sum = 0, $j = 0; $j < 5; $j++)
$sum = $sum * 85 + $ords[$j];
for ($j = 3; $j >= 0; $j--)
$output .= chr($sum >> ($j * 8));
}
}
if ($state === 1)
return "";
elseif ($state > 1) {
for ($i = 0, $sum = 0; $i < $state; $i++)
$sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
for ($i = 0; $i < $state - 1; $i++) {
try {
if(false == ($o = chr($sum >> ((3 - $i) * 8)))) {
throw new Exception('Error');
}
$output .= $o;
} catch (Exception $e) { /*Dont do anything*/ }
}
}
return $output;
}
function decodeFlate($data) {
return #gzuncompress($data);
}
function getObjectOptions($object) {
$options = array();
if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
$options = explode("/", $options[1]);
#array_shift($options);
$o = array();
for ($j = 0; $j < #count($options); $j++) {
$options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
if (strpos($options[$j], " ") !== false) {
$parts = explode(" ", $options[$j]);
$o[$parts[0]] = $parts[1];
} else
$o[$options[$j]] = true;
}
$options = $o;
unset($o);
}
return $options;
}
function getDecodedStream($stream, $options) {
$data = "";
if (empty($options["Filter"]))
$data = $stream;
else {
$length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
$_stream = substr($stream, 0, $length);
foreach ($options as $key => $value) {
if ($key == "ASCIIHexDecode")
$_stream = $this->decodeAsciiHex($_stream);
elseif ($key == "ASCII85Decode")
$_stream = $this->decodeAscii85($_stream);
elseif ($key == "FlateDecode")
$_stream = $this->decodeFlate($_stream);
elseif ($key == "Crypt") { // TO DO
}
}
$data = $_stream;
}
return $data;
}
function getDirtyTexts(&$texts, $textContainers) {
for ($j = 0; $j < count($textContainers); $j++) {
if (preg_match_all("#\[(.*)\]\s*TJ[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\(.*\))\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\[.*\])\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
}
}
function getCharTransformations(&$transformations, $stream) {
preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
for ($j = 0; $j < count($chars); $j++) {
$count = $chars[$j][1];
$current = explode("\n", trim($chars[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
$transformations[str_pad($map[1], 4, "0")] = $map[2];
}
}
for ($j = 0; $j < count($ranges); $j++) {
$count = $ranges[$j][1];
$current = explode("\n", trim($ranges[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$_from = hexdec($map[3]);
for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
} elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$parts = preg_split("#\s+#", trim($map[3]));
for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
}
}
}
}
function getTextUsingTransformations($texts, $transformations) {
$document = "";
for ($i = 0; $i < count($texts); $i++) {
$isHex = false;
$isPlain = false;
$hex = "";
$plain = "";
for ($j = 0; $j < strlen($texts[$i]); $j++) {
$c = $texts[$i][$j];
switch($c) {
case "<":
$hex = "";
$isHex = true;
$isPlain = false;
break;
case ">":
$hexs = str_split($hex, $this->multibyte); // 2 or 4 (UTF8 or ISO)
for ($k = 0; $k < count($hexs); $k++) {
$chex = str_pad($hexs[$k], 4, "0"); // Add tailing zero
if (isset($transformations[$chex]))
$chex = $transformations[$chex];
$document .= html_entity_decode("&#x".$chex.";");
}
$isHex = false;
break;
case "(":
$plain = "";
$isPlain = true;
$isHex = false;
break;
case ")":
$document .= $plain;
$isPlain = false;
break;
case "\\":
$c2 = $texts[$i][$j + 1];
if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
elseif ($c2 == "n") $plain .= '\n';
elseif ($c2 == "r") $plain .= '\r';
elseif ($c2 == "t") $plain .= '\t';
elseif ($c2 == "b") $plain .= '\b';
elseif ($c2 == "f") $plain .= '\f';
elseif ($c2 >= '0' && $c2 <= '9') {
$oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
$j += strlen($oct) - 1;
$plain .= html_entity_decode("&#".octdec($oct).";", $this->convertquotes);
}
$j++;
break;
default:
if ($isHex)
$hex .= $c;
elseif ($isPlain)
$plain .= $c;
break;
}
}
$document .= "\n";
}
return $document;
}
}

PHP Conditional > how to know what didn't match?

if i have statement:
$a = 1;
$b = 2;
$c = 3;
if($a == 1 && $b == 2 && $c == 3)
{
echo 'correct';
}
else
{
echo 'what variable's weren't matched';
}
Is there any way of knowing what didn't watch instead of writing everything separately?
Cheers!
No. Your expression was turned into a boolean, so apart from checking the equality(s) again you cannot find out which triggered the "false".
You need to test each individually, but you could do something like this:
$a = 1;
$b = 2;
$c = 3;
$a_matched = $a == 1;
$b_matched = $b == 1;
$c_matched = $c == 1;
if($a_matched && $b_matched && $c_matched)
{
echo 'correct';
}
else
{
if (!$a_matched) echo 'a did not match!';
if (!$b_matched) echo 'b did not match!';
if (!$c_matched) echo 'c did not match!';
}
but that's less clear than just:
$a = 1;
$b = 2;
$c = 3;
if($a == 1 && $b == 2 && $c == 3)
{
echo 'correct';
}
else
{
if (!$a == 1) echo 'a did not match!';
if (!$b == 2) echo 'c did not match!';
if (!$c == 3) echo 'b did not match!';
}
Actually, heh, I take back my comment. You can rely on the boolean short-circuiting to set a variable indicating the last part of the conditional which was true:
if (($x = 'a') && $a == 1 && ($x = 'b') && $b == 2 && ($x = 'c') && $c == 3) {
echo "correct\n";
} else {
echo "$x is wrong\n";
}
Note, I would never write this in production code because it's goofy and very hard to understand what's supposed to be going on. But fun to fiddle with, at least.
Nope! That's not possible. You can make life a lot simpler by using arrays, though:
$results = array(1, 2, 4);
$expected = array(1, 2, 3);
$count = count($results);
$wrong = array();
for($i = 0; $i < $count; $i++) {
if($results[$i] !== $expected[$i]) {
$wrong[] = $i;
}
}
if(count($wrong) > 0) {
echo "There were wrong ones. They were at positions: " . implode(', ', $wrong);
} else {
echo "All good!";
}
For example.

Categories