PHP Check if 2 variables are the same, like a test - php

I need help to check if variables (from a database) are the same, like a test.
First I was using just "==", but I saw this: http://php.net/manual/en/language.operators.comparison.php , and now I'm using "===". But it still doesn't work.
My code:
$uids = array();
$trues = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($uids, $row['UID']);
} while ($row1 = mysqli_fetch_assoc($result1)) {
array_push($uids, $row1['UID']);
} while ($row2 = mysqli_fetch_assoc($result2)) {
array_push($uids, $row2['UID']);
}
for ($i = 0; $i < count($uids); $i++) {
$r = 0;
if ($row['question1'] === $row['uAnswer1']) {
$r++;
} else {
$r = $r;
} if ($row['question2'] === $row['uAnswer2']) {
$r++;
} else {
$r = $r;
} if ($row['question3'] === $row['uAnswer3']) {
$r++;
} else {
$r = $r;
} if ($row['question4'] === $row['uAnswer4']) {
$r++;
} else {
$r = $r;
} if ($row['question5'] === $row['uAnswer5']) {
$r++;
} else {
$r = $r;
} if ($row['question6'] === $row['uAnswer6']) {
$r++;
} else {
$r = $r;
} if ($row['question7'] === $row['uAnswer7']) {
$r++;
} else {
$r = $r;
} if ($row['question8'] === $row['uAnswer8']) {
$r++;
} else {
$r = $r;
} if ($row['question9'] === $row['uAnswer9']) {
$r++;
} else {
$r = $r;
} if ($row['question10'] === $row['uAnswer10']) {
$r++;
} else {
$r = $r;
}
array_push($trues, $r);
echo $uids[$i] . " [" . $r . "]<br>";
}
print_r($trues);
}
What the result is: https://hastebin.com/uxitoyoyib.php
So it actually says everything is right, but I know that it isn't. Can you help me with this?
Thanks!

Compare variables like
if ( strtolower(trim($row['question5'])) === strtolower(trim($row['uAnswer5'])) )
Remove spaces if added with strings, convert the string in lowercase to the exact match of both strings.

use
if ($row['question4'] == $row['uAnswer4']) {
//do something
}
and try to print your 2 variable.

You can use the strcmp() or strcasecmp() functions or the === operator.

Related

how to write recursion using loops

I want to write recursive code using loops instead of recursion function. because recursion take too much time to execute and even fails.This is counting user in both side of binary tree using recursion.i want to achieve this task using loops. please help me to achieve this task.thanks in advance.I will very thank full to you.
function countActiveMembers($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countLeftActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($leftm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
function countRightActive($mid){
if ($mid == null) {
return 0;
}
$c = 0;
include("conn.php");
$query = $conn->prepare('SELECT leftm, rightm, package_choose FROM member WHERE user_id = ?');
$query->bind_param('s', $mid);
$query->execute();
$query->bind_result($leftm, $rightm, $package_choosen);
if ($query->fetch()) {
$query->close();
$conn->close();
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($rightm);
}
} else {
$query->close();
$conn->close();
}
return $c;
}
I hope you can appreciate that this is difficult to test, so hopefully you can understand it enough to help.
One of the big performance issues in any system is file/database access and opening and closing connections etc. is always a slow process. This routine loads all the members in the start and passes the data around rather than continually using the database...
function countActiveMembers( $members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
// Fetch the data from the $members list, using $mid as the index
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
$package_choosen = $members[$mid]['package_choose'];
if ($package_choosen == 1) {
$c = 0;
} else {
$c = 1;
}
if (isset($leftm) == false && isset($rightm) == false) {
return $c;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
function countLeftActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($leftm)) {
$c = $c + countActiveMembers($members, $leftm);
}
return $c;
}
function countRightActive($members, $mid){
if ($mid == null) {
return 0;
}
$c = 0;
$leftm = $members[$mid]['leftm'];
$rightm = $members[$mid]['rightm'];
if (isset($leftm) == false && isset($rightm) == false) {
return 0;
}
if (isset($rightm)) {
$c = $c + countActiveMembers($members, $rightm);
}
return $c;
}
// Use your own database credentials
$conn = mysqli_connect("172.17.0.3", "root","a177fgvTRw", "test" );
$result = $conn->query('SELECT user_id, leftm, rightm, package_choose
FROM member');
$members = [];
// Read all the members in and index them by the user_id
while ($row = $result->fetch_assoc()) {
$members[$row["user_id"]] = $row;
}
// Not entirely sure how you use it,but this shows passing the members into the start function
echo countActiveMembers($members, 1);

How to insert coordinates of a table into an array in PHP

I am making the game battleships in PHP and I need to make it so that the computer randomly chooses 5 coordinates(x, y), and they have to be in a straight line (column or row). How do I make it so the coordinates are in a line and how do I connect the coordinates to the table cells?
Here's what I have so far:
<?php
session_start();
$i=0;
$start=1;
$st=65;
$l=0;
$polje=array();
$x=(mt_rand(0, 10));
$y=(mt_rand(0, 10));
for($q=0; $q<5; $q++){
$polje[$l]=array($x, $y);
}
echo "<table id='table'>\n";
while ($i<11){
$ascii=chr($st);
echo "<tr>";
for($k=0; $k<11; $k++, $start++){
if($k==0){
echo "<td>$i</td>";
}
else if($i==0){
echo "<td class='td2'>$ascii</td>";
$ascii++;
}
else{
echo "<td class='td1'> </td>";
}
}
echo "</tr>";
$i++;
}
?>
This is what the table looks like:
I like this kind of challenge.
Of course, there is a lot of ways, better ways to do this, with OOP, but you can get the point.
Read the comments through the code and if you have any doubts feel free to ask.
I did some treatment to avoid ships overlapping each other, and random deployment.
const BOARD_SIZE = 10; //10x10 board
const SUBMARINE = 1;
const DESTROYER = 2;
const BATTLESHIP = 3;
const AIRCRAFTCARRIER = 4;
$ships_available = [];
//populate with some data based on game rule
array_push($ships_available, SUBMARINE);
array_push($ships_available, SUBMARINE);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, AIRCRAFTCARRIER);
$board = [];
while(count($ships_available) > 0) {
deployShip($board, $ships_available);
}
$lastColumnLetter = chr(ord('A')+ BOARD_SIZE-1);
//print table
echo "<table border='1' align='center'>";
echo "<tr><td></td><td>".implode('</td><td>',range(1, BOARD_SIZE))."</td></tr>";
for($i = 'A'; $i <= $lastColumnLetter; $i++) {
echo "<tr><td>".$i."</td>";
for($j=0; $j < BOARD_SIZE; $j++) {
echo "<td align='center'>";
echo $board[$i][$j] ?: ' ';
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
exit;
function array_merge_custom($array1, $array2) {
foreach($array2 as $key => $value) {
foreach($value as $k => $v) {
$array1[$key][$k] = $v;
}
}
return $array1;
}
function deployShip(&$board, &$ships_available) {
$randomShipKey = array_rand($ships_available);
$ship = $ships_available[$randomShipKey];
$beginCoordinates = getRandomCoordinates();
$coordinates = getShipCoordinates($board, $beginCoordinates, $ship);
if(!$coordinates) {
return false;
}
unset($ships_available[$randomShipKey]);
$board = array_merge_custom($board,$coordinates);
}
function getRowNumberByLetter($letter) {
return array_search($letter, range('A','Z'));
}
function getRowLetterByNumber($number) {
$letters = range('A','Z');
return $letters[$number];
}
function getRandomCoordinates() {
return ['row' => chr(mt_rand(ord('A'), (ord('A') + BOARD_SIZE-1))), 'col' => mt_rand(0,BOARD_SIZE -1)];
}
function getShipCoordinates($board, $beginCoordinates, $ship) {
if(isset($board[$beginCoordinates['row']][$beginCoordinates['col']])) {
return false; //anchor position already taken
}
if($ship == 1) {
$return[$beginCoordinates['row']][$beginCoordinates['col']] = 1;
return $return;
}
$shipArraySize = $ship -1;
$directions = ['left', 'right', 'up', 'down'];
$tries = 10;
while($tries > 0) {
$tries--;
$direction = $directions[array_rand($directions)];
$return = [];
switch($direction) {
case 'left':
if(($beginCoordinates['col'] - $shipArraySize) < 0) { //check if can go left
break;
}
for($colBegin = ($beginCoordinates['col'] - $shipArraySize), $colEnd = $beginCoordinates['col']; $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colBegin])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'right':
if(($beginCoordinates['col'] + $shipArraySize) > BOARD_SIZE -1) { //check if can go right
break;
}
for($colBegin = $beginCoordinates['col'], $colEnd = ($beginCoordinates['col'] + $shipArraySize); $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colEnd])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'up':
if((getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize) < 0) { //check if can go up
break;
}
for($rowBegin = (getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize), $rowEnd = getRowNumberByLetter($beginCoordinates['row']); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
case 'down':
if((getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize) > BOARD_SIZE -1) { //check if can go down
break;
}
for($rowBegin = getRowNumberByLetter($beginCoordinates['row']), $rowEnd = (getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
}
}
return false;
}

While loop and if - execute only one time

I have following code:
while($row = mysql_fetch_assoc($result))
{
if(strtolower($message) == $row['question'])
{
msg($row['answer']);
update($row['question']);
} else {
dodaj(strtolower($message), '', 0);
}
}
and I would like to execute function dodaj(); only one time, not a few times. How to do it? Please help, thank you very much.
Greetings.
Use a variable to remember if you called dodaj.
$called_dodaj = false;
while($row = mysql_fetch_assoc($result))
{
if(strtolower($message) == $row['question'])
{
msg($row['answer']);
update($row['question']);
} elseif (!$called_dodaj) {
dodaj(strtolower($message), '', 0);
$called_dodaj = true;
}
}
Use a break statement:
while($row = mysql_fetch_assoc($result))
{
if(strtolower($message) == $row['question'])
{
msg($row['answer']);
update($row['question']);
} else {
dodaj(strtolower($message), '', 0);
break;
}
}
EDIT: I assumed you meant to stop processing results once dodaj() was called. However, if you mean that you only want to call dodaj() one time, use a flag variable:
$dodajCalled = false;
while($row = mysql_fetch_assoc($result))
{
if(strtolower($message) == $row['question'])
{
msg($row['answer']);
update($row['question']);
} elseif (!$dodajCalled) {
dodaj(strtolower($message), '', 0);
$dodajCalled = true;
}
}

how to sort SQL result in an existing sorting function

Hello I have this sorting function ine one template of CMS. I would like to add if the condition is the second one:
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
I want to add the following MySQL result to show also
$result = mysql_query("SELECT niches.name, niches.record_num FROM niches ORDER BY name ASC");
which is used in this template for sorting:
include($basepath.'/templates/template.channel_item_title.php');
Any ideas how this can be integrated inside the first code function?
So here is the code of the main index template:
<?
session_start();
if(($_REQUEST[mode] == 'favorites' || $_REQUEST[mode] == 'my_uploads') && !$_SESSION[username]) {
header("Location: /login.php");
}
include('admin/db.php');
include($basepath.'/includes/inc.seo.php');
$cacheName = $_SERVER[REQUEST_URI];
$cacheResult = getCache($cacheName);
$cacheTotalPages = getCache("total_pages$cacheName");
if($cacheResult && $cacheTotalPages) {
$array = $cacheResult;
$total_pages = $cacheTotalPages;
}
else {
include($basepath.'/includes/inc.index_queries.php');
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
if($thispage != 'favorites' && $_GET[mode] != 'my_uploads') {
setCache($cacheName,$array,$overall_cache_time);
setCache("total_pages$cacheName",$total_pages,$overall_cache_time);
}
}
$thisfile = 'index';
$webpage="index";
if($isMobile) {
include($basepath.'/templates/mobile.overall_header.php');
}
else {
include($basepath.'/templates/template.overall_header.php');
}
if(empty($_GET[mode]) && !$_GET[page]) {
include($basepath.'/templates/template.home.php');
}
if($webpage=="index" && empty($_GET[mode]) && !$_GET[page])
{}
else
{
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
}
else {
if($isMobile) {
include($basepath.'/templates/mobile.content_item.php');
}
else
{
include($basepath.'/templates/template.content_item.php');
}
}
}
}
else {
echo "Sorry, no results were found.";
}
}
if($isMobile) {
include($basepath.'/templates/mobile.overall_footer.php');
}
else {
include($basepath.'/templates/template.overall_footer.php');
}
?>
I don't think I get your question, but we have to start somewhere...
<?php
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
Next block of code:
<?php
$result = mysql_query("SELECT niches.name, niches.record_num FROM niches ORDER BY name ASC");
if(is_array(result)) {
foreach($result as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.channel_item_title.php');
}

Why does this PHP function cycle endlessly?

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);

Categories