Change '-' to variable and use this variable to call exact value - php

For example:
$k = "+";
$q = 8;
echo $array[$q+1];
But I want the following:
echo $array[$q$k1];
So it basically says "call the value of array which is 8+1 so 9." and if I want to call 7 I can do $k = "-".

In PHP, you can not treat operators as variables.
Still, there two basic ways you can achieve the same effect.
You can use a conditional and specify the values accordingly:
$r = 1; //the value you're adding; moved to a variable for clarity
$op = '+'; //+ means add; anything else means subtract
echo $array[$q + ($op === '+' ? $r : -$r)];
//or
if($op === '+') {
echo $array[$q + $r];
} else {
echo $array[$q - $r];
}
Or you can change the operation into a multiplication:
echo $array[$q + (($op === '+' ? 1 : -1) * $r)];
Either form will work; it's just a matter of what is most convenient for your code.

Related

PHP OO - Associative array of object instances, resetting on each click

My first ever question on here as I'm completely stuck, so apologies if I leave out any key information - please let me know!
I am creating a PHP Battleships game and trying to use full OO. I'm really close, however, an array for one of my classes does not hold any updates I make to it.
First off, I dynamically
created a HTML table with an onclick event - which passes the coordinates to a JS function.
I then make an AJAX call in jQuery:
function shotFired(row, column) {
var coords = {
x: row,
y: column
};
$.post("data/game_controller.php", {
jsonCoords: JSON.stringify(coords)
}, function(results) {
console.log(results)
console.log(results[4])
var playerShotResult = results[0];
var computerShotX = results[1] + 1;
var computerShotY = results[2] + 1;
var computerShotResult = results[3];
var positionsClicked = document.getElementById("computer_" + row + "," + column)
switch (playerShotResult) {
case "MISS":
positionsClicked.classList.add("miss");
break;
case "HIT":
positionsClicked.classList.add("hit");
break;
case "Already Hit":
document.getElementById("outputMessage").innerHTML = result
break;
default:
console.log("Player shot defaulted");
}
}, "json")
I then use game_controller.php to handle the request and call shotFired:
<?php
session_start();
require("../classes/Game.class.php");
if (isset($_POST['jsonCoords'])) {
if (isset($_SESSION['newGame'])) {
$game = unserialize($_SESSION['newGame']);
$coords = json_decode($_POST['jsonCoords']);
$results = $game->shotFired($coords->x, $coords->y);
echo json_encode($results);
}
}
shotFired from the Game.php Class file, gets an instance of the Fleet class called computer, and runs the checkPosition function:
public function shotFired($x, $y)
{
$computer = $this->getComputer();
$playerHit = $computer->checkPosition(($x - 1), ($y - 1));
$computerGrid = $computer->getBattleshipsGrid();
$computerHit = $this->simulateComputerShot();
return [$playerHit, $computerHit[0], $computerHit[1], $computerHit[2], $computerGrid];
}
checksPosition checks the State of the Position instance in the BattleshipGrid array, and then attempts to update the array with a H or M - using a standard setter method:
public function checkPosition($x, $y): string
{
$positionObj = $this->battleshipsGrid["(" . $x . "," . $y . ")"];
$positionState = $positionObj->getState();
if ($positionState == "#") {
$positionObj->setState("M");
return "MISS";
} elseif ($positionState == "M" || $positionState == "H") {
return "Already Fired";
} else {
$positionObj->setState("H");
return "HIT";
}
}
For reference, I set the Battleships board in the constructor for Fleet.php:
// Populate associative array with instances of position
for ($y = 0; $y < $gridSize; $y++) {
for ($x = 0; $x < $gridSize; $x++) {
$coordinates = "(" . $x . "," . $y . ")";
$this->battleshipsGrid[$coordinates] = new Position($x, $y);
}
}
It works directly after it has been set - however, on the next onclick event, the H or M value is reset to it's previous value?
Seen here in console output
After a couple of hours, the closest I've come to is passing byRef in the setState function (didn't make a difference).
I've seen some notes on array_map, but I'm not sure this is what I'm looking for?
For ref, this is how I output the battleshipGrid to the console:
public function getBattleshipsGrid()
{
$readableGrid = "";
$grid = $this->battleshipsGrid;
foreach ($grid as $coordsID => $positionObj) {
$readableGrid .= "\n" . $coordsID . ": " . $positionObj->getState();
}
return $readableGrid;
}
Apologies for the long post, but I didn't want to leave anything out. Any and all help would be extremely appreciated!
Many thanks
It looks like you're not saving the state of the coordinates of the hits. If you are using the eloquent model, and setState is changing the attribute's value, make sure that you call $positionObj->save() as php does not save state on each ajax request. You will need to use a database or some sort of storage to have the server 'remember' that you clicked a specific location.

PHP | Make a validation check whether the number has a decimal point == x.00 or not

Em, I don't know how to explain this. I hope you'll get the point.
I've variables:
$a = 10; //int
$b = 2.5; //float
$c = $a * $b; //I know this return will be float: 25
From those variables, I want to make a statement as follows:
if (//the value of $c have a decimal point == x.00) {
echo $c;
} else {
echo '';
}
Did you get it? What I want is that when the decimal point of $c is x.00 (like 25.00, 10.00, etc), the $c will be printed. But if the decimal point is NOT x.00 (eg 25.50, 25.7, etc) then $c will NOT be printed.
I've read some references but still don't understand how to do it.
Thank you. I hope you understand what I mean.
PHP has is_integer() - https://www.php.net/manual/en/function.is-integer.php
Or if you want to check manually, then you can compare against the rounded down (floor) and rounded up (ceil) values:
if ($a==Floor($a) && $a==Ceil($a)){
// Whole Number
} else {
// Has decimal point value
}
You can try like below.
<?php
function is_decimal_exist( $value ) {
return is_numeric( $value ) && floor( $value ) != $value;
}
$my_value = "10.00";
if( is_decimal_exist ( $my_value ) ) {
echo ''; // Decimal Present, Do Not Print $my_value
}else{
echo $my_value; // Print $my_value
}
?>
Much easier. Just check if the integer of the number is equal == to the number:
if ((int)$c == $c) {
echo $c;
} else {
echo '';
}

if condition with using only single variable in php

i want to check two string in if condition equal or not but it is give me return true whats the problem please check my code.
$if = "(1 == 2)";
if($if){
echo 'hi';
}
see my code above.. it always return hi.. what i was done wrong please help me.
its return only hi.. i have many condition store in if variable but my first condition not fulfill so i want it now.. please suggest me.
my full code is here..
$if = "(1 == 2)";
if($location_search != ''){
$if .= " && ('."$location_search".' == '."$get_city".')";
}
if($location_state != ''){
$if .= " && ('."$location_state".' == '."$get_state".')";
}
if($location_bedrooms != ''){
$if .= " && ('."$location_bedrooms".' == '."$get_bedrooms".')";
}
if($location_bathrooms != ''){
$if .= ' && ('."$location_bathrooms".' == '."$get_bathrooms".')';
}
if($location_type != ''){
$if .= ' && ('."$location_type".' == '."$get_type".')';
}
if($location_status != ''){
$if .= " && ('".$location_status."' == '".$get_status."')";
}
if($if){
echo 'hi';
}
i added this code but always return tru and print hi. please help me.
Collect all of your variables in one array and go through it with foreach checking everyone. If one of variables is empty, assign false to your if variable. Will write code later, when will be next to computer.
Your variable $if is a declared as a string due to the double quotes. How about this
$a = 1;
$b = 2;
if ($a == $b) {
// When $a equals $b
echo "hi";
} else {
// When $a doesn't equal $b
$if is a string, and not null. In PHP this means it's true. I think if you remove the quotes, it should instead evaluate the expression to false.
Remove the double quotes here " (1 == 2)"
You can remove quotes (with quotes it's a normal string), but keep in mind that this is bad approach and should not be used like this.
Working code:
$if = (1 == 2); // evaluates to true
if($if) {
// code
}

Modify scope variable

I had a string variable in php with this value 000001422 and I used to modify it in order to display it in a better way:
<?php
$hits = "000001422";
$var = (int)$hits;
$var = abbreviateNumber($var);
echo $var; ?>
This is the function to crop and abbreviate the number in something like 1,4k
function abbreviateNumber(value) {
var newValue = value;
if (value >= 1000) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor( (""+value).length/3 );
var shortValue = '';
for (var precision = 2; precision >= 1; precision--) {
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision));
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,'');
if (dotLessShortValue.length <= 2) { break; }
}
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
newValue = shortValue+suffixes[suffixNum];
}
return newValue;
}
This worked great.
Now I'm trying to switch my code to AngularJS (I'm still learning it) so my value it's not a php variable but a scope variable received from an $http request. I have something like {{x.count}} which is my 000001422 but I would like to display it in the same way I did before.
I tryed to $hits = "{{x.count}}"; but it's not working and I think it's not the right approach. Can you address me in the right way to handle this?
EDIT:
I removed the initial zeros converting the value into an int with {{x.count - 0}} but still need to apply my abbreviate function.

Wordpress QR Code Widget

Basically, I've been trying to make a simple Wordpress widget that displays a QR code with the URL of the current page. I'm using a modififed version of the simple text widget that parses PHP too.
function the_qrcode($permalink = '', $title = '') {
if($permalink && $title == '') {
$permalink = 'http://eternityofgamers.com/forums';
$title = 'Forums';
}
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data=' .$permalink. '" alt="QR: ' .$title. '"/>;
}
Can someone tell me what's wrong with this? I get a 500 error when I add it to functions.php.
You will need to use the urlencode() function. Generally as a rule of thumb all querystring values should be url encoded.
function the_qrcode( $permalink = '' ) {
if($permalink == '') {
$permalink = 'http://eternityofgamers.com/forums';
}
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data='.urlencode($permalink);
}
Now you can create your QR code with:
the_qrcode(the_permalink());
Also, you had a very bad missing equals sign. It is very important to understand the difference between = and ==. If you don't, no matter the context = and == mean two different things. = assigns the right hand side to the left. == returns true or false whether the left and right hand side are loosely equal (loosely because casting will be used if the sides are not of the same type).
Look at this example (Codepad demo):
$a = 5;
$b = 10;
if($a = 6) {
echo "This always appears because when you assign a truthy (all non-zero numbers are true) to a variable, true is returned.\n";
echo "Also a should now equal six instead of five: " . $a . "\n";
}
if($b == 10) {
echo "This will work as expected because == is a comparison not an assignment.\n";
echo "And b should still be 10: " . $b;
}
Try with:
<?php
function the_permalink( $permalink ) {
if ($permalink == '') {
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data=http://eternityofgamers.com/forums" alt="QR Code">';
} else {
echo '<img src="http://api.qrserver.com/v1/create-qr-code/?data='.$permalink;
}
}
?>
(I've corrected a bunch of syntax errors)

Categories