Php Booleans not working correctly? - php

I have the following code, I seem to be having problems with booleans in php, when ever i dump out the value of bCreatedEvent it is just empty, what am i doing wrong and I'm using booleans wrong? It also fails my logic check so i can redirect at the bottom. I'm fairly new to php, but thought most of this should work similar to c/c++.
$dbTheatreCMS = new TheatreCMSDB();
$iEventID = $dbTheatreCMS->InsertNewEvent($sTitle, $sCompany, $iCreateID, $sNotes, $sPrePrice, $sRegPrice);
$bEventCreated = False;
echo "bEventCreated1 = " . $bEventCreated . "<br/>";
$bEventInfoInserted = True;
$bEventRolesInserted = True;
if ($iEventID > 0)
{
$bEventCreated = true;
if (isset($_POST["Venues"], $_POST["EventDates"]))
{
$aiVenueIDs = $_POST["Venues"];
$adtEvents = $_POST["EventDates"];
if (count($adtEvents) == count($aiVenueIDs)) // These should be the same length
{
for ($i = 0; $i < count($adtEvents); $i++)
{
$bEventInfoInserted &= ($dbTheatreCMS->InsertNewEventInfo($iEventID, $aiVenueIDs[$i],$adtEvents[$i]) > 0) ? true :false;
}
}
}
if (isset($_POST["Troupers"], $_POST["Roles"]))
{
$trouperIDs = $_POST["Troupers"];
$roles = $_POST["Roles"];
if (count($trouperIDs) == count($roles))
{
for ($i = 0; $i < count($trouperIDs); $i++)
{
$bEventInfoInserted &= ($dbTheatreCMS->InsertNewTroupeInfo($iEventID, $trouperIDs[$i],$roles[$i]) > 0)? true:false;
}
}
}
}
echo "bEventCreated = " . $bEventCreated . "<br/>";
echo "bEventInfoInserted = " . $bEventInfoInserted . "<br/>";
echo "bEventRolesInserted = " . $bEventRolesInserted . "<br/>";
$bEventCreated = $bEventCreated & $bEventInfoInserted & $bEventRolesInserted;
echo "$bEventCreated = " . $bEventCreated . "<br/>";
if($bEventCreated == True)
{
echo "<script type='text/javascript'>window.localStorage.href = 'some page.php';</script>";
}
output
bEventCreated1 =
bEventCreated =
bEventInfoInserted = 1
bEventRolesInserted = 1
0 = 0

echo false will look empty use var_dump($bEventCreated)
Also & is a bitwise operator I think you mean &&
$bEventCreated = $bEventCreated & $bEventInfoInserted & $bEventRolesInserted;

Make sure you always use identical or not identical comparison operators when doing a boolean condition:
if($bEventCreated === TRUE)

If a value is false, it will not echo or print a value. See for example:
<?php
$true = true;
$false = false;
echo $true."\n";
echo $false."\n";
var_dump($true)."\n";
var_dump($false);
?>
http://codepad.org/98bR4bfn

There are some quirks with booleans in PHP. This two links may help:
http://pl.php.net/manual/en/language.types.boolean.php
http://pl.php.net/manual/en/language.types.string.php#language.types.string.casting

When you echo a variable it is first converted to a string.
When FALSE or NULL is converted to a string they are converted to an empty string, "". TRUE is converted to "1". Arrays are converted to "Array". Resources are undefined although they are currently converted like "Resource #N". Objects will throw an error if they don't implement __toString().

Related

Loop from array not executed

I am working on an android app that should create some records on a MySQL database.
This is the PHP file that receives the POST values from the app.
As you may see, there are three arrays that collect specific POST.
The first and second loops are working fine and executing the related guardar_post_media() function.
But the third loop is not executed and there are real values on the variables inside the third array.
May be there is something wrong that I can´t detect, may be you can.
<?php
require_once '../mis_php_functions/funciones_basicas.php';
if($_SERVER['REQUEST_METHOD']=='POST'){
$val39 = $_POST['val39'];
$val40 = $_POST['val40'];
$val46 = $_POST['val46'];
$val48 = $_POST['val48'];
$val50 = $_POST['val50'];
$val52 = $_POST['val52'];
$val54 = $_POST['val54'];
$val56 = $_POST['val56'];
$val58 = $_POST['val58'];
$val60 = $_POST['val60'];
$val62 = $_POST['val62'];
$val64 = $_POST['val64'];
$val65 = $_POST['val65'];
$val67 = $_POST['val67'];
$val69 = $_POST['val69'];
$val71 = $_POST['val71'];
$val73 = $_POST['val73'];
$val75 = $_POST['val75'];
$val77 = $_POST['val77'];
$val79 = $_POST['val79'];
$val81 = $_POST['val81'];
$val82 = $_POST['val82'];
$val83 = $_POST['val83'];
$val84 = $_POST['val84'];
$val85 = $_POST['val85'];
$val86 = $_POST['val86'];
$val87 = $_POST['val87'];
$val88 = $_POST['val88'];
$val89 = $_POST['val89'];
$val100 = $_POST['val100'];
$val101 = $_POST['val101'];
$val102 = $_POST['val102'];
$val103 = $_POST['val103'];
$val104 = $_POST['val104'];
$status = 1;
$post = guardar_post($val40,$val39,$val100,$val102,$status,$val103);
if ($post != false) {
$fotos = array($val48,$val50,$val52,$val54,$val56,$val58,$val60,$val62,$val64);
$arrayLength = count($fotos);
echo "Numero de fotos ".$arrayLength;
$i = 0;
while ($i < $arrayLength)
{
if ($fotos[$i] == 0){
}
else{
guardar_post_media(1,$fotos[$i],$val102,$val100,$post);
}
echo "<br />".$fotos[$i] ."<br />";
$i++;
}
$videos = array($val67,$val69,$val71,$val73,$val75,$val77,$val79,$val81,$val83);
$arrayLength2 = count($videos);
echo "Numero de videos ".$arrayLength2;
$i = 0;
while ($i < $arrayLength2)
{
if ($videos[$i] == 0){
}
else{
guardar_post_media(2,$videos[$i],$val102,$val100,$post);
}
echo "<br />".$videos[$i] ."<br />";
$i++;
}
$youtube = array($val85,$val86,$val87,$val88,$val89);
$arrayLength3 = count($youtube);
echo "Numero de youtube ".$arrayLength3;
$i = 0;
while ($i < $arrayLength3)
{
if ($youtube[$i] == 0){
}
else{
guardar_post_media(3,$youtube[$i],$val102,$val100,$post);
}
echo "<br />".$youtube[$i] ."<br />";
$i++;
}
sendMessageNuevoPost($val39,$val102,$val103,$val104); // envio de push
}
else{
echo 'error';
}
}
?>
You have:
if ($youtube[$i] == 0){
}
else {
}
But POST vars are all strings. Change to:
if ($youtube[$i] == "0"){
}
else {
}
In otherwords, an equality on a string to numerical 0 will be true in your cases. And thus your else never executes.
*** Edit. PROOF
$test1 = "filename.dat";
$test2 = "2939";
$test3 = "some useful data";
$test4 = "0";
if ($test1 == 0) {
// Dont do anything
}
else {
echo "Do Work 1.";
}
if ($test2 == 0) {
// Dont do anything
}
else {
echo "Do Work 2.";
}
if ($test3 == 0) {
// Dont do anything
}
else {
echo "Do Work 3.";
}
if ($test4 == 0) {
// Dont do anything
}
else {
echo "Do Work 4.";
}
Only echoes out Do Work 2.. All other echo()s are not run because the equality of a string to a number 0 will return true except in those cases where the string also is numerical, and then the interpreter will compare the numerical values.
As how this relates to the OP's question: It can be inferred that the OP's POST vars must contain some non-numerical data because the OP insists that the 3rd array is populated:
But the third loop is not executed and there are real values on the variables inside the third array.
I will add likely the loop is executed, but not giving the expected the results due the reasons so mentioned.
Tested on PHP 5 and 7.

Split results into variables after mysqli query

I have following:
if($broj_podstanica != "" && $broj_podstanica != 0) {
$uzmi_podstanice = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT $broj_podstanica";
$pronasao_sve_podstanice = $db->query($uzmi_podstanice);
while($sifrePodstanica = $pronasao_sve_podstanice->fetch_assoc()) {
$sifreIzbrojane = $sifrePodstanica['sifra'] . ",";
$izbaci_zarez = explode(",", $sifreIzbrojane);
if (!isset($izbaci_zarez[0])) {
$izbaci_zarez[0] = "";
$pods0 = "";
} else {
$pods0 = $izbaci_zarez[0];
}
if (!isset($izbaci_zarez[1])) {
$izbaci_zarez[1] = "";
$pods1 = "";
} else {
$pods1 = $izbaci_zarez[1];
}
if (!isset($izbaci_zarez[2])) {
$izbaci_zarez[2] = "";
$pods2 = "";
} else {
$pods2 = $izbaci_zarez[2];
}
}
echo "1:" . $pods0;
echo "2:" . $pods1;
echo "3:" . $pods2;
echo "4:" . $pods3;
echo "5:" . $pods4;
}
Query gives me results: 30313233.
After while loop I tried to control variables $pods0, $pods1, $pods2, $pods3 and $pods4 but It gives me result for first variable only; $pods0 is 30..
Is it possible to get other values from variables?
You have some problems with your code, first of all, you do not need use isset() function, it always returns true because of the variable is exists. Secondly, if $izbaci_zarez[1] is empty you do not need to set it again with an empty value. The last thing, store the data in an array instead of a variable and it will not limit your variables count (Because of it will hard to follow) and set the values to their correct index.
if($broj_podstanica != "" && $broj_podstanica != 0) {
$uzmi_podstanice = "SELECT * FROM objekt WHERE vrsta_objekta = '2' ORDER BY sifra ASC LIMIT $broj_podstanica";
$pronasao_sve_podstanice = $db->query($uzmi_podstanice);
$i = 1;
$pods = array();
while($sifrePodstanica = $pronasao_sve_podstanice->fetch_assoc()) {
$sifreIzbrojane = $sifrePodstanica['sifra'] . ",";
$izbaci_zarez = explode(",", $sifreIzbrojane);
$pods[$i] = $izbaci_zarez[0];
$i++;
}
echo "1:" . $pods[1];
echo "2:" . $pods[2];
echo "3:" . $pods[3];
echo "4:" . $pods[4];
echo "5:" . $pods[5];
// and etc...
}

strpos returns true when using clearly different strings

I'm taking data from an excel using phpexcel, like this:
$number = $objPHPExcel->getActiveSheet()->getCell('A3')->getValue();
number is clearly a number, okay? so, after that I want to know if $number exists on the word $elem:
if(strpos($elem,$number) !== false) //está?
{
$answer = true;
}
the problem is that when I test it with this data, the $answer is true, and it shouldn't be:
$number = 11001456
$elem = '10001033.jpg'
So... what's wrong here?
PD: I'm going to post the entire code so you can see it, If I try to do (string)$number then the code crashes, it exceeds time execution.... (using cakephp)
The important thing is located at the function SearchPhoto... you will see the strpos there...
public function admin_load() //esto sirve para cargar un excel...
{
if($this->request->is('post'))
{
$data = $this->request->data;
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
require_once WWW_ROOT . '/excelWorker/Classes/PHPExcel/IOFactory.php';
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);
$objPHPExcel = PHPExcel_IOFactory::load($data['People']['excel']['tmp_name']);
$dir = WWW_ROOT . "img/photos";
$files = scandir($dir);
$batchPeople = array();
for($i = 2; $i <= $data['People']['num']; $i++)
{
$batchPeople[$i-2]['People']['fullname'] = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue();
$batchPeople[$i-2]['People']['floor'] = $objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue();
$batchPeople[$i-2]['People']['country'] = $objPHPExcel->getActiveSheet()->getCell('D'.$i)->getValue();
$batchPeople[$i-2]['People']['day'] = $objPHPExcel->getActiveSheet()->getCell('F'.$i)->getValue();
$batchPeople[$i-2]['People']['month'] = $objPHPExcel->getActiveSheet()->getCell('G'.$i)->getValue();
$batchPeople[$i-2]['People']['photo'] = $this->SearchPhoto($objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue(),$files);
}
// $this->People->saveMany($batchPeople);
}
}
function SearchPhoto($number, $array)
{
$answer = '';
$getOut = false;
foreach($array as $elem)
{
if(strcmp($elem,'.') != 0 && strcmp($elem,'..') != 0)
if(strpos($elem,$number) !== false) //está?
{
echo 'coinciden--> '. $number . ',' . $elem;
echo '<br>';
$answer = $elem;
$getOut = true;
}
if($getOut)
break;
}
return $answer;
}
This should work for you:
(BTW: You use $number in the code and not $num)
<?php
$num = 11001456;
$elem = "10001033.jpg";
if(strpos($elem, (string)$num) !== false) {
echo "yes";
}
?>
For more information about strpos() look into the manual: http://php.net/manual/en/function.strpos.php
And a quote from there:
needle:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
echo chr($number); // p
echo strpos($elem, 'p'); // 10 (which is p in $elem)
I ended up using preg_match to solve my problem... I still don't know what's wrong with using strpos... because it works on all the sites I made expect this particular case!
In case anyone wondering what's the exact solution:
$text = $B;
$pattern = '/'.$A.'/';
preg_match($pattern,$text,$matches);
if(isset($matches[0]))
$answer = true;

Why doesn't my PHP foreach work?

$start = true;
$new = "";
foreach($array as $val)
{
if($start = true && $val != " ")
{
$start = false;
$new .= strtoupper($val);
}
elseif($val == " ")
{
$new .= " ";
$start = true;
}
else
{
$new .= strtolower($val);
}
$start = false;
}
Basically what happens is $start NEVER becomes false AND everything becomes capitalized. So it looks like the first if IS running, but for some reason NEVER SETS $start to false.
I cannot stress it enough: use the yoda condition
if(true == $var)
or generally:
if(CONSTANT == $VARIABLE)
and not
if($VARIABLE == CONSTANT) //which you'd wrongly type as "="
PHP would have told you what went wrong in that case - no matter how tired you are.
Looking for this bug (it happens to the best of the best too) is frustrating.
Let the tool (PHP) be supportive to you, don't make it work against you.
That was on a more general note. As for your problem, it's doable with a one-liner:
<?php
$array = "hEllo woRlD";
var_dump(ucwords(strtolower($array)));
$start = true is an assignment, not a comparison. Use ==.
You're using a single equals in your test, which means "assignment". You probably meant == (equality), but in this case, with booleans, you don't need to compare at all:
$start = true;
$new = "";
foreach($array as $val)
{
if($start && $val != " ") // <-- remove the = true here
{
$start = false;
$new .= strtoupper($val);
}
elseif($val == " ")
{
$new .= " ";
$start = true;
}
else
{
$new .= strtolower($val);
}
$start = false;
}
Right now, it's getting interpreted as "Set $start to true && $val != " "" - definitely not what you intended.
$start = true && $val != " " means:
$start = (true && $val != " ")
$start = ($val != " ")
$start = !($val == " ") // $start is true except when $val is a single space.
I believe you meant $start == true.
Are you just trying to upper case the first character of every word? If so, look into ucwords.

How to set this cases depends on if rule

if i've the following
$x = "go";
$y = "went";
$z "gone";
and i need to set title where title will be
$title = $x; //only if "y" empty no care about "z" if empty or not
$title = $x . " - " . $y; // if "y" not empty and "z" is empty
$title = $y . " - " . $z; // if "z" not empty and "y" not empty
this is my try but field and/or looks so permeative (i'm noob)
$empty = ""; // i've creaty empty example
$x = "go";
$y = "went";
$z "gone";
if ($y==$empty) {
$title = $x; // output should be go
} else if($y!=$empty && $z==$empty) {
$title = $x . " - " . $y; // output should be go - went
} else if($y!=$empty && $z!=$empty) {
$title = $y . " - " . $z; // output should be went - gone
} else {
$title = $x; // output should be go
}
do anyone have better suggestion ! thanks a lot
$title = empty($y) ? $x : (empty($z) ? $x."-".$y : $y."-".$z);

Categories