PHP Switch-Case not working with certain string? - php

I'm trying to get switch/case to work with some variables and they aren't working and I am wondering why:
function convert_time($time_code) {
switch ($time_code) {
case "8:00a-10:00p":
return 1;
break;
}
}
Then the code that calls this function is:
$testvariable = "8:00a-10:00p";
$testtimecode = covert_time($testvariable);
echo "TTC: $testtimecode";
It always outputs "TTC:"
I went to PhpFiddle and tested it and it also doesn't work there, but I couldn't find a way to make a link to it like in jsfiddle.
However, if I do this code:
$time_code = "8:00a-10:00a";
if ($time_code == "8:00a-10:00a") {echo "yes";} else {echo "no";}
It will echo yes.
So my question is, what about the format of my 8:00a-10:00a is breaking the switch? and is it fixable.

Nevermind.
I found my problem and it was a typo.
It should have been 8:00a-10:00a, and it was 8:00a-10:00p.
sorry!

Got this to work on my local server:
function convert_time($time_code) {
switch ($time_code) {
case "8:00a-10:00p": return 1;
}
}
$testvariable = "8:00a-10:00p";
$testtimecode = convert_time($testvariable);
echo "TTC: $testtimecode";
not quite sure what could've happened on your end, possibly something wrong with your server itself but give this a shot.

Related

PHP function (shortcut) use

I have set in myFile.php this function:
function monthLanguage()
{
if ($this->lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
}
I was thinking to wrap this if statement into a function to call it where is needed as a kind of short code.
I call it like this:
monthLanguage();
but I get error message: Call to undefined function
Any help on how to reach my short code intent?
Are you including the monthLanguage function the file you are using it in? Also, I spotted two issues with this code. You are not initiating the array called $dayName and nothing is being returned so the function will not send back output. It should be like this.
function monthLanguage()
{
$dayName = array();
if ($this->lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
return $dayName;
}
Also, the $this is not clear since that is usually used in the scope of a class, so perhaps you need to set the function like this:
function monthLanguage($lang)
{
$dayName = array();
if ($lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
return $dayName;
}
And you would then call the function in PHP like this:
monthLanguage($this->lang);
Or like this:
monthLanguage($lang);
But it is unclear where this function is being placed or used, so clarify that to decide which is the best way to handle.
I don't think you can use $this->lang - it's usually reserved for a method if I'm not mistaken.
Try replacing the function with this, should work like a charm.
function monthLanguage($lang) {
if ($lang=='italian')//this statement is requared many times within the file!
{
$dayName[]="Dom";
$dayName[]="Lun";
$dayName[]="Mar";
$dayName[]="Mer";
$dayName[]="Gio";
$dayName[]="Ven";
$dayName[]="Sab";
}else
{
$dayName[]="Sun";
$dayName[]="Mon";
$dayName[]="Tue";
$dayName[]="Wed";
$dayName[]="Thu";
$dayName[]="Fri";
$dayName[]="Sat";
}
}

use goto inside function php

Is there a way to define global label (something like variables) for PHP goto, in order to use it inside function declaration. I want to do the following:
function myFunction() {
if (condition) {
goto someLine;
}
}
someLine:
// ....
myFunction();
when I use this code it says
PHP Fatal error: 'goto' to undefined label "someLine"
I know that it is not recommended to use goto statement. But I need it in my case. I know that perhaps always there are alternatives of goto, just in my case it would make the code a little easier and understandable
You cannot goto outside of a function I believe: http://php.net/manual/en/control-structures.goto.php
Direct Quote:
This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one.
This might have to do with the fact that php is parsed and jumping out of a function will cause a memory leak or something because it was never properly closed.
Also as everyone else said above, really you don't need a goto. You can just return different values from the function and have a condition for each. Goto is just super bad practice for modern coding (acceptable if you are using basic).
Example:
function foo(a) {
if (a==1) {
return 1;
} elseif (a==3) {
return 2;
} else {
return 3;
}
}
switch (foo(4)) { //easily replaceable with elseif chain
case 1: echo 'Foo was 1'; break; //These can be functions to other parts of the code
case 2: echo 'Foo was 3'; break;
case 3: echo 'Foo was not 1 or 3';
}
There's no way to jump in or out of a function. But since you state that you need it, here's an alternative route.
function myFunction() {
if (condition) {
return true;
}
return false;
}
someLine:
// ....
$func = myFunction();
if($func == true) goto someLine;
As previously stated you can't. As for "I need it", I highly doubt this. Whatever code you have at someLine: can easily be made into a function that you can call from the other if needed.
yeah there's a way as long as that function is declared on the same php file or is included if its on another script,
the best way to jump on to someline is to return that goto code of yours dude so that if function is called a return value is received.. hope this helps
function foo($b="30")
{
$a=30;
if($a==intval($b))
return "someline:goto
someline";
}
try{
eval(foo());
}
catch(IOException $err)
{
exit($err);
}
/*someline is somewhere here
for example */

what will happen if we have more statements in coding after function return code?

I have basic question for you guys
i have php function which verifies and creates the file handler name for the given type,
however i just want to know if the following code goes to a else, will the next lines of the coding of creating the guid will be executed or will it be ignored ?
private function fileFormat($type=false){
if($type=='CreditCard')
$prefix='CC-';
elseif($type=='DirectDebit')
$prefix='DD-';
else
return false;
$date = $prefix.'-'.date('d-m-Y', time());
$guid = '' . md5($date) . '.csv';
return $guid;
}
They will be ignored. Anything after return statement will not be executed.
Whenever the return false is executed the following lines will not be executed. However you must make sure at the spot you call your function you can 100% distinguish between the return values from return false and a return $guid
No more lines execute after a return statement is executed.
Simply it will not execute (ignore) the lines following return.
Not to beat a dead horse, now that there are a number of answers stating the same thing... but here is my clarification.
After a return is executed, no remaining code will be executed. The way you have setup your code is fine, assuming you want a false returned if neither of the $types are encountered. This is a common control flow and is preferred over setting a flag and checking the flaw before return.
if ($myCondition_1) {
$a = 1;
} elseif ($myCondition_2) {
$a = 2;
} else {
return False;
}
other_operation_on_a($a);
return $a;
Is preferred (for me) over:
$a = False;
if ($myCondition_1) {
$a = 1;
} elseif ($myCondition_2) {
$a = 2;
}
if ($a !== False) {
other_operation_on_a($a);
}
return $a;
The function will return and everything after the encountered return statement will not be executed.
They'll be ignored because the return will be executed by the else (default) case.
The idea is that control is returned to the calling method.... So those lines will never execute.
For example if your IDE is good, you are given warnings in the case of redundant statements after the return e.g:
function PrintHelloWorld()
{
if($userPresent)
{
echo "Hello World" ;
}
return "World empty!";
$something = "blah" ; //redundant (will never execute)
$something+="Blah" ; //redundant (will never execute)
//A good IDE should give warnings. But you usually see them as grayed out
}

How do I verify that this function is a string in PHPUnit?

Here's the code for my original PHP code:
public function outputText() {
$i = 1;
foreach($this->sorted_data as $this->data) {
echo "$i. ".$this->data[0]."<br/>";
$i++;
}
}
And here's the code for the PHPUnit:
public function testVerify() {
$yn = new SortThisData();
$yn->readFile("input.txt");
$output = $yn->outputText();
$this->assertTrue(is_string($output));
//if(!is_string($yn->get()))
// return false;
//$this->assertNotEmpty($yn->get());
}
The class is called SortThisData in the original PHP file.
When I used gettype(), it said it was null. I'm trying to verify that it is a string so it can pass in PHPUnit. Is there a way I can do this?
You're looking for assertInternalType().
Update: I didn't realize you were echoing the output. You will probably need to use output buffering to capture the text.
public function testVerify() {
$yn = new SortThisData();
$yn->readFile("input.txt");
// start output buffering and capture the output
ob_start();
$yn->outputText();
$output = ob_get_clean();
$this->assertInternalType('string', $output);
}
No disagreement with Baylor's answer. To answer the question, as asked, what you had was also good enough:
$this->assertTrue(is_string($output));
Or you could have done:
$this->assertEquals('string',gettype($output));
(The advantage of the latter is, when it fails, it will also tell you the type of $output; assertTrue will only tell you that something failed.)
assertInternalType() does exactly that, but was only introduced in PHPUnit 3.5, and you will still find PHPUnit 3.4 in use on some machines.

How would I call a method from a class with a variable?

Given this class:
class Tacobell{
public function order_taco(){
echo "3 Tacos, thank you.";
}
public function order_burrito(){
echo "Cheesy bean and rice, please";
}
}
$lunch = new Tacobell;
$lunch->order_burrito();
$lunch->order_taco();
How would I do something like this?
$myOrder = 'burrito';
$lunch->order_.$myOrder;
Obviously that code is bunk--but shows what I'm attempting to do better than trying to explain it away.
And maybe I'm going about this all wrong. I thought about a method with a switch statement, pass in burrito or taco, then call the right method from there. But then I have to know the end from the beginning, and I may potentially have lots of methods and I'd rather not have to update the switch statement everytime.
Thanks!
How about something like this?
class Tacobell {
public function order_burrito() {
echo "Bladibla.\n";
}
public function order($item) {
if (method_exists($this, "order_$item")) {
$this->{'order_' . $item}();
} else {
echo "Go away, we don't serve $item here.\n";
}
}
}
You would call it using $lunch->order('burrito');, which looks much cleaner to me. It puts all the uglyness in the method Tacobell::order.
$lunch->{'order_' . $myOrder}();
I do agree the design is a little iffy, but that's how to do it at least.
I think call_user_func is what you're looking for:
http://us3.php.net/call_user_func
You can pass it the string you suggested. See example #3 for calling a method of a class.
simple enough
$order = 'order_burrito';
$lunch->$order();

Categories