In a PHP project I am working on right now, I have some code similar to this:
$allVarsTrue = TRUE;
if ($foo && $bar) {
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
$allVarsTrue = FALSE; // if $x fails the test, $allVarsTrue is set to false
}
}
} else { // if either $foo and $bar is false, $allVarsTrue is set to false
$allVarsTrue = FALSE;
}
if ($allVarsTrue) {
echo "True";
} else {
echo "False";
}
I would like to write this more succinctly, something like this
// This code does not work.
if ($foo &&
$bar &&
for ($x=1;$x<=5;$x++) {
somerandomtest($x);
}) {
echo "True";
} else {
echo "False";
}
How can I rewrite the existing code more succinctly?
One option is to move your loop into its own function:
function performTests() {
for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
return TRUE;
}
if($foo && $bar && performTests()) {
…
} else {
…
}
Wrap it in a function:
function testStuff($foo, $bar){
if (!$foo || !$bar) {
return FALSE;
}
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
return FALSE;
}
}
return TRUE;
}
And then:
if (testStuff($foo, $bar)) {
echo "True";
} else {
echo "False";
}
You can't really. However, you can break the for loop as soon as first test is failed
if ($foo && $bar) {
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
$allVarsTrue = FALSE; // if $x fails the test, $allVarsTrue is set to false
break; //no point in firther iterating
}
}
} else { // if either $foo and $bar is false, $allVarsTrue is set to false
$allVarsTrue = FALSE;
}
Related
i am working on validation and comparisons!! i have a field that can contain the value $val=0 or $val="some-value" or $val="" or $val=0 basically i want the $val="0"or $val=0 to be validated as true..
if($val){
//works for $val="some-value"
//doesnot work for $val=0 or $val="0";
} else
{
//works corrent for $val=""
}
one conditional approach i used is
$val="";
if($val || $val==0){
echo "true";
}
else
{
//should be false but it is true
echo "false";
}
did you try this?
$val = "";
if ($val == '0') {
echo "TRUE";
# code...
}
elseif ($val == "") {
echo "FALSE";
}
There is a useful php native function is_null
if (is_null($val) || $val === "") {
//invalid
} else {
//valid
}
You can use PHP integer casting & can do it like this:
if ((int) $val === 0) {
return true;
} else {
return false;
}
Hope this helps!
i am working on an addon, but i got a problem
[22:03:08] [CRITICAL]: "Could not pass event 'pocketmine\event\player\PlayerInteractEvent' to 'MTeamPvP v1.0.0 Beta': Argument 1 passed to MCrafters\TeamPvP\GameManager::__construct() must be an instance of MCrafters\TeamPvP\TeamPvP, none given, called in C:\Users\USER\Desktop\Taha\FlashCraft PE\lobby 1\plugins\DevTools\src\MCrafters\TeamPvP\TeamPvP.php on line 120 and defined on MCrafters\TeamPvP\TeamPvP
[22:03:08] [NOTICE]: InvalidArgumentException: "Argument 1 passed to MCrafters\TeamPvP\GameManager::__construct() must be an instance of MCrafters\TeamPvP\TeamPvP, none given, called in C:\Users\USER\Desktop\Taha\FlashCraft PE\lobby 1\plugins\DevTools\src\MCrafters\TeamPvP\TeamPvP.php on line 120 and defined" (E_RECOVERABLE_ERROR) in "/DevTools/src/MCrafters/TeamPvP/GameManager" at line 13
also sorry for the different error broadcasting
code : (please don't care about the other classes except GameManager and TeamPvP)
TeamPvP.php:
<?php
namespace MCrafters\TeamPvP;
use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat as Color;
use pocketmine\utils\Config;
use pocketmine\event\Listener;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\player\PlayerDeathEvent;
use pocketmine\math\Vector3;
use pocketmine\level\Position;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\Player;
use pocketmine\block\Block;
use pocketmine\item\Item;
use pocketmine\block\WallSign;
use pocketmine\block\PostSign;
use pocketmine\scheduler\ServerScheduler;
class TeamPvP extends PluginBase implements Listener
{
// Teams
public $reds = [];
public $blues = [];
public $gameStarted = false;
public $yml;
public function onEnable()
{
// Initializing config files
$this->saveResource("config.yml");
$yml = new Config($this->getDataFolder() . "config.yml", Config::YAML);
$this->yml = $yml->getAll();
$this->getLogger()->debug("Config files have been saved!");
$this->getServer()->getScheduler()->scheduleRepeatingTask(new Tasks\SignUpdaterTask($this), 15);
$this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->getServer()->getLogger()->info(Color::BOLD . Color::GOLD . "M" . Color::AQUA . "TeamPvP " . Color::GREEN . "Enabled" . Color::RED . "!");
}
public function isFriend($p1, $p2)
{
if ($this->getTeam($p1) === $this->getTeam($p2) && $this->getTeam($p1) !== false) {
return true;
} else {
return false;
}
}
// isFriend
public function getTeam($p)
{
if (in_array($p, $this->reds)) {
return "red";
} elseif (in_array($p, $this->blues)) {
return "blue";
} else {
return false;
}
}
public function setTeam($p, $team)
{
if (strtolower($team) === "red") {
if (count($this->reds) < 5) {
if ($this->getTeam($p) === "blue") {
unset($this->blues[array_search($p, $this->blues)]);
}
array_push($this->reds, $p);
$this->getServer()->getPlayer($p)->setNameTag("§c§l" . $p);
$this->getServer()->getPlayer($p)->teleport(new Vector3($this->yml["waiting_x"], $this->yml["waiting_y"], $this->yml["waiting_z"]));
return true;
} elseif (count($this->blues) < 5) {
$this->setTeam($p, "blue");
} else {
return false;
}
} elseif (strtolower($team) === "blue") {
if (count($this->blues) < 5) {
if ($this->getTeam($p) === "red") {
unset($this->reds[array_search($p, $this->reds)]);
}
array_push($this->blues, $p);
$this->getServer()->getPlayer($p)->setNameTag("§b§l" . $p);
$this->getServer()->getPlayer($p)->teleport(new Vector3($this->yml["waiting_x"], $this->yml["waiting_y"], $this->yml["waiting_z"]));
return true;
} elseif (count($this->reds) < 5) {
$this->setTeam($p, "red");
} else {
return false;
}
}
}
public function removeFromTeam($p, $team)
{
if (strtolower($team) == "red") {
unset($this->reds[array_search($p, $this->reds)]);
return true;
} elseif (strtolower($team) == "blue") {
unset($this->blues[array_search($p, $this->blues)]);
return true;
}
}
public function onInteract(PlayerInteractEvent $event)
{
$p = $event->getPlayer();
$teams = array("red", "blue");
if ($event->getBlock()->getX() === $this->yml["sign_join_x"] && $event->getBlock()->getY() === $this->yml["sign_join_y"] && $event->getBlock()->getZ() === $this->yml["sign_join_z"]) {
if (count($this->blues) < 5 && count($this->reds) < 5) {
$this->setTeam($p->getName(), $teams[array_rand($teams, 1)]);
$s = new GameManager();
$s->run();
} else {
$p->sendMessage($this->yml["teams_are_full_message"]);
}
}
}
public function onEntityDamage(EntityDamageEvent $event)
{
if ($event instanceof EntityDamageByEntityEvent) {
if ($event->getEntity() instanceof Player) {
if ($this->isFriend($event->getDamager()->getName(), $event->getEntity()->getName()) && $this->gameStarted == true) {
$event->setCancelled(true);
$event->getDamager()->sendMessage(str_replace("{player}", $event->getPlayer()->getName(), $this->yml["hit_same_team_message"]));
}
if ($this->isFriend($event->getDamager()->getName(), $event->getEntity()->getName())) {
$event->setCancelled(true);
}
}
}
}
public function onDeath(PlayerDeathEvent $event)
{
if ($this->getTeam($event->getEntity()->getName()) == "red" && $this->gameStarted == true) {
$this->removeFromTeam($event->getEntity()->getName(), "red");
$event->getEntity()->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
} elseif ($this->getTeam($event->getEntity()->getName()) == "blue" && $this->gameStarted == true) {
$this->removeFromTeam($event->getEntity()->getName(), "blue");
$event->getEntity()->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
}
foreach ($this->blues as $b) {
foreach ($this->reds as $r) {
if (count($this->reds) == 0 && $this->gameStarted == true) {
$this->getServer()->getPlayer($b)->getInventory()->clearAll();
$this->removeFromTeam($b, "blue");
$this->getServer()->getPlayer($b)->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
$this->getServer()->broadcastMessage("Blue Team won TeamPvP!");
} elseif (count($this->blues) == 0 && $this->gameStarted == true) {
$this->getServer()->getPlayer($r)->getInventory()->clearAll();
$this->removeFromTeam($r, "red");
$this->getServer()->getPlayer($r)->teleport($this->getServer()->getLevelByName($this->yml["spawn_level"])->getSafeSpawn());
}
}
}
}
}//class
GameManager.php :
<?php
namespace MCrafters\TeamPvP;
use pocketmine\scheduler\ServerScheduler as Tasks;
class GameManager
{
public $reds;
public $blues;
public $gst;
public $gwt;
public function __construct(\MCrafters\TeamPvP\TeamPvP $plugin)
{
parent::__construct($plugin);
$this->plugin = $plugin;
}
public function run()
{
$this->reds = $this->plugin->reds;
$this->blues = $this->plugin->blues;
if (count($this->reds) < 5 && count($this->blues) < 5) {
$this->gst = Tasks::scheduleRepeatingTask(new Tasks\GameStartTask($this), 20)->getTaskId();
Tasks::cancelTask($this->gwt);
} else {
$this->gwt = Tasks::scheduleRepeatingTask(new Tasks\GameWaitingTask($this), 15)->getTaskId();
}
}
}
namespace correct, class and file name correct, and all other functions from other classes have nothing to do with this :) check the line where there is GameManager::run() in TeamPvP class.
i already know there is one about this, but i didn't understand it.
Thank You for your help.
You have a type hint
public function __construct(\MCrafters\TeamPvP\TeamPvP $plugin)
{
parent::__construct($plugin);
$this->plugin = $plugin;
}
So when you go to instantiate MCrafters\TeamPvP\GameManager you have to pass it an instance of \MCrafters\TeamPvP\TeamPvP
$team = new \MCrafters\TeamPvP\TeamPvP();
$manager = new \MCrafters\TeamPvP\GameManager($team)
I'm newbie, and just want to asking about programming stuff. I hope you guys help me getting understand :)
which is more efficient in coding and performance between this two function?
first function using nested condition, and second function using simple condition,
which is better to be implemented?
function optionOne()
{
$a = getData();
$return = array();
if ($a === false) {
$return['error'] = true;
} else {
$b = getValue();
if ($b === false) {
$return['error'] = true;
} else {
$c = getVar();
if ($c === false) {
$return['error'] = true;
} else {
$return['error'] = false;
$return['message'] = 'congrat!';
}
}
}
return $return;
}
function optionTwo()
{
$return = array();
$a = getData();
if ($a === false) {
$return['error'] = true;
return $return;
}
$b = getValue();
if ($b === false) {
$return['error'] = true;
return $return;
}
$c = getVar();
if ($c === false) {
$return['error'] = true;
return $return;
} else {
$return['error'] = false;
$return['message'] = 'congrat!';
}
return $return;
}
thank you before guys,
function option()
{
$return=array();
$return['error'] = true;
switch(getData()){
case false:
return $return;
break;
case true:
if(getValue()==false){return $return;}
else{
if(getVar()==false){return $return;}
else{
$return['error'] = false;
$return['message'] = 'congrat!';}
}
break;
default:
return 'getData() return null value';
break;
}
}
i was tried to applied the switch method to your function, as one of your option too
A neater option would be to make the 3 functions throw an exception when there's an error instead of returning boolean false. That's what exceptions are for anyway. Then in your function you can just wrap the calls in a try-catch block.
function option {
$return = array();
try {
$a = getData();
$b = getValue();
$c = getVar();
$return['error'] = false;
$return['message'] = 'congrat!';
} catch(Exception e) {
$return['error'] = true;
}
return $return;
}
function nonrecgen($min, $max, $amount) {
for($i=0;$i<$amount;$i++) {
$NrArray[$i] = rand($min,$max);
echo $NrArray[$i];
do {
for($j=0;$j<=$i;$j++) {
if ($NrArray[$j] == $NrArray[$i]) {
$NrArray[$i] = rand($min,$max); }
}
$Reccuring = false;
if ($i > 0) {
for($k=0;$k<=$i;$k++) {
if ($NrArray[$k] == $NrArray[$i]) {
$Reccuring = true; }
}
}
}
while ($Reccuring = true);
}
Return $NrArray;
}
$Test = nonrecgen(0,1,2);
print_r($Test);
I wanted to look into how to generate an array of nonreccuring numbers and while this is certainly not the most efficient way I believe, I can't seem to figure out why it loops endlessly on the first iteration. I tried logical analysis over and over, but there has to be something I'm missing.
do {
...
} while ($Reccuring = true);
Because your while statement sets $Reccuring to true, instead of evaluating it.
Try:
do {
...
} while ($Reccuring === true);
Other than the = to == you were also resetting the $Recurring in the wrong place:
<?
function nonrecgen($min, $max, $amount)
{
for($i=0;$i<$amount;$i++)
{
$NrArray[$i] = rand($min,$max);
do
{
for($j=0;$j<=$i;$j++)
{
if ($NrArray[$j] == $NrArray[$i])
{
$NrArray[$i] = rand($min,$max);
}
}
if ($i > 0)
{
for($k=0;$k<=$i;$k++)
{
if ($NrArray[$k] == $NrArray[$i])
{
$Reccuring = true;
}
}
}
$Reccuring = false;
}
while ($Reccuring == true);
}
return $NrArray;
}
$Test = nonrecgen(0,2,5);
echo "<pre>";
print_r($Test);
?>
You're currently assigning a value rather than checking (which will always be true).
Change it to: while ($Reccuring == true);
I have a page that includes/embeds a file that contains a number of functions.
One of the functions has a variable I want to pass back onto the page that the file is embedded on.
<?php
include('functions.php');
userInGroup();
if($user_in_group) {
print 'user is in group';
} else {
print 'user is not in group';
}
?>
function within functions.php
<?php
function userInGroup() {
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group = FALSE;
}
}
}?>
I am unsure as to how I can pass the value from the function userInGroup back to the page it runs the conditional if($user_in_group) on
Any help is appreciated.
Update:
I am userInGroup(array("STAFF","STUDENTS","FACULTY"));
which then is
<?php
function userInGroup($group_access) {
session_start();
if(isset($_SESSION['user_session'])) {
$username = $_SESSION['user_session'];
$group_session = $_SESSION['group_session'];
$user_full_name = $_SESSION['user_full_name'];
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group = FALSE;
}
} return $user_in_group;
} else {
print 'not logged in';
}
?>
Easiest way:
$user_in_group = userInGroup();
function userInGroup() {
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group == FALSE;
}
}
return $user_in_group;
}
Use the return statement.
You can use your original function with one minor modification:
<?php
function userInGroup() {
**global $user_in_group;**
foreach($group_access as $i => $group) {
if($group_session == $group) {
$user_in_group = TRUE;
break;
} else {
$user_in_group = FALSE;
}
}
}?>