if condition fails while checking json array values - php

i have a simple json array. in which i have two objects. now i am checking it for some specific values , if found do some thing , if not found do another thing. But i dont know why if condition runs both blocks. true and false both blocks are executed. please help.
$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring);
$count = count($jsonarr->like);
for ($r = 0; $r < $count; $r++)
{
if ($jsonarr->like[$r]->username == 'abc' && $jsonarr->like[$r]->password == 'abc')
{
echo 'Match';
}else
{
echo 'No Match';
}
}
is it not like regular if condition ?

It's showing both blocks because you are looping thru the json array which contains two items. One matching your condition, the other not matching. Here is a simpler version that does not use a loop but just tests your value if in the array. Notice the 'true' flag in the json_decode as well.
<?php
$jsonstring = '{"like":[{"username":"abc","password":"abc"},{"username":"def","password":"def"}]}';
$jsonarr = json_decode($jsonstring, true);
$testArray = $jsonarr['like'];
$loginArray = array('username'=>'abc','password'=>'abc');
if (in_array($loginArray,$testArray)) {
echo 'match found, do login';
} else {
echo "no match, do something else";
}
?>

Related

how to use comparison in php

i want to compare array $list_matkul which is from database to a string inside php
why my response "adalah" always showing false in my comparison
this is my code
<?php
require_once 'DB_Functions.php';
$response = array();
$db = new DB_Functions();
if (isset($_POST['no']) && isset($_POST['semester'])) {
$no = $_POST['no'];
$semester = $_POST['semester'];
$list_matkul = array();
$response['error'] = false;
$sks = $db->getSks($no,$semester-1);
$list_matkul = $db->getAllMatkulMhs($no,$semester);
$response['matkul_list'] = array_values($list_matkul);
for ($x = 0; $x < count($list_matkul); $x++) {
if (array_values($list_matkul[$x]) == "matkul_1"){
$response['adalah'] = true;
$x+=999999;
} else {
$response['adalah'] = false;
}
}
echo json_encode($response,JSON_PRETTY_PRINT);
}
?>
here is my json response
{
"error": false,
"matkul_list": [
{
"nama_matkul": "matkul_1"
},
{
"nama_matkul": "matkul_2"
},
{
"nama_matkul": "matkul_4"
},
{
"nama_matkul": "matkul_3"
}
],
"adalah": false
}
Without a Loop
Firstly, you can do this without using a loop at all.
//convert your array to a flat array of just names
$names = array_column($list_matkul, 'nama_matkul');
//set `adalah` value based on if the name was found in the array
$response['adalah'] = in_array('matkul_1', $names);
//echo json
echo json_encode($response,JSON_PRETTY_PRINT);
With a Loop
If you insist on using a loop, in my opinion it would be easier to see what is going on if you use a foreach loop instead of a for loop. With a for loop, you need to keep up with the $x variable, but this isn't necessary in a foreach loop.
Also, you can get rid of your else statement by just ending the loop early.
//value defaults to false
$response['adalah'] = false;
//loop through all rows of array
foreach($list_matkul as $row) {
//if name in array is "matkul_1"
if($row['nama_matkul'] == 'matkul_1') {
//set value to true if the above statement is true
$response['adalah'] = true;
//end loop, we know `adalah` is true, no need to loop anymore
break;
}
}
echo json_encode($response,JSON_PRETTY_PRINT);
Your logic seems wrong:
if (array_values($list_matkul[$x]) == "matkul_1"){
The function array_values returns an array and you are comparing it to a string. Maybe you meant to write
array_values($list_matkul)[$x] == "matkul_1"
Also, instead of $x+=999999; you could simply write break; ;)
Manual references:
https://www.php.net/manual/en/function.array-values.php
https://www.php.net/manual/en/control-structures.break.php

Error when comparing string value and string value from array in PHP

I'm trying to compare 2 values, one coming from post data and the other one coming from an array, the weird thing is, when I compare them, all of the records show that they are not equal but some of the values have equal values:
What I actually need to do is to unset those values that are not equal in the post data sent.
$a = $_POST['time']; (Value is 01:03)
$testarray = array("12:30","01:03","03:30");
for($x = 0; $x < count($testarray);$x++){
if($a === $testarray[$x]){
echo "ok";
}
else
{
echo "not";
}
}
All of the my results are showing not, even though there is a similar value on one of the contents in the array.
What seems to be the problem here? I've check the values and the data types are both string.
use in_array
$a = $_POST['time']; //(Value is 01:03)
$testarray = array("12:30","01:03","03:30");
if( in_array($a, $testarray))
{
echo "ok";
}
else
{
echo "not";
}
Simple use in_array to Checks if a value exists in an array
$a = $_POST['time'];
$testarray = array("12:30","01:03","03:30");
if (in_array($a, $testarray))
{
echo "Match found";
}
else
{
echo "Match not found";
}

in_array() keeps appending values if looping through db rows

I need to identify every instance where a value in one array (needle) occurs in another array (haystack). in_array() seems to be my best option, and the code below works perfectly until I need to use it on rows fetched from a db - it keeps appending values instead of setting them each time it's called.
While I can't actually use unset() in this situation, I was surprised to discover that even that didn't seem to resolve the problem.
UPDATE - Example of what's being returned
I temporarily changed the db values so that $needles has only value per row (in order to make it possible to sort through the values filling up my screen ;-))
False;
False; False; True;
False; False; True; False; True;
False; False; True; False; True; False; True;
False; False; True; False; True; False; True; False;
This works correctly
(I've posted a functional example here)
$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');
foreach ($needles as $needle) {
if (in_array($needle, $haystack) ) {
$Match = 'True';
}
else {
$Match = 'False';
}
}
This keeps appending values - Edited to reflect the code I'm using
$Customer_Categories_Arr = array('Casual','Trendy');
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$Product_Categories_Arr[]=$row["Taste_Category"];
// Use when column contains CSV
// $Product_Categories_Arrx = explode(',', trim($Product_Categories_Arr[0]));
foreach ($Product_Categories_Arr as $Product_Category_Arr) {
if (in_array($Product_Category_Arr, $Customer_Categories_Arr)){
$Matches_Product_Category = "True";
} else {
$Matches_Product_Category = "False";
}
echo $Product_Category_Arr, ', ', $Matches_Product_Category, '; ';
}
}
}
It is not really clear what you are trying to do. But maybe this would help:
$customerCategories = array('Casual', 'Trendy');
if( $stmt->columnCount() ){
while( $row = $stmt->fetch( PDO::FETCH_ASSOC )){
$productCategoryRow = $row[ 'Taste_Category' ];
// If it is not working, try uncommenting the next line
// $productCategories = [];
$productCategories = explode( ',', trim( $productCategoryRow ));
$match = "False";
foreach( $productCategories as $productCategory ){
if( in_array( $productCategory, $customerCategories )){
$match = "True";
}
echo $match . ";";
}
}
}
This prints your result on the screen every time a loop is done. Is this what you mean?
If you want the second block of code to do what the first block of code (which works correctly) does, then the second block should look like this -
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$needle =$row["product_var"];
$Match = "False";
if (in_array($needle, $haystack)){
$Match = "True";
}
}
}
You don't need do use the foreach because that is replaced by the while loop in the second block.
I am going to try an solve this. I think the problem is with:
$needles[]=$row["product_var"];
I think this should be:
$needles=$row["product_var"];
The column "product_var" contains an CSV (as you mentioned), so I can make an example like this:
$csv = "jake;john;alex;kim";
An example with brackets ($needles[]):
for($i=0; $i<5; $i++) {
$needles[] = explode(";", $csv);
echo(count($needles).", ");
}
returns:
1, 2, 3, 4, 5,
edit (for more explaining):
if I use print_r I see the array expanding, exactly how it happens in your example:
step 1: it adds an array to $needles with values ('jake','john','alex','kim')
step 2: it adds an array to $needles, so it contains 2x the values ('jake','john','alex','kim')
step 3: it adds an array to $needles, so it contains 3x the values ('jake','john','alex','kim')
etc.
Now without the brackets ($needles):
for($i=0; $i<5; $i++) {
$needles = explode(";", $csv);
echo(count($needles).", ");
}
This returns:
4, 4, 4, 4, 4,
And every time the array simply contains the values ('jake','john','alex','kim') -which is what you want.
Could this explain the "expanding values"? (or am I just doing something really stupid which has nothing to do with your problem??)
edit:
If this is what is going wrong, then you are adding to an array, instead of only using the new array from $row["product_var"] (hope this makes any sense; it seems I am pretty bad at explaining what's happening).

How do I use PHP to compare one variable to any odd number instance of another variable?

I want to compare the session[name] to all the even instances of text.
For example:
$_SESSION['name'] === $text[1] or $text[2] or $text[4] or $text[6]
The problem with doing it like the way above is that the code above will limit to only 6. Is there any way to just say "compare this to all the even instances of '$text' "?
Basically what I'm trying to do is say:
Compare $_SESSION['name'] to all even info from the $Text array.
So for example if this was my array:
$text = array("info0", "info1", "info2", "info3")
I would want to compare something to all the even info instances in the array(ie: info0, info2)
The code:
//compare the strings
if ($_SESSION['name'] === $text[0] && $_SESSION['pass'] == $text[1]) {
//echo "That is the correct log-in information";
header("Location: home.php");
} else {
echo "That is not the correct log-in information.";
}
XaxD's answer is good, and probably what you are interested in, but if you are using an associative array and want to look at every other element of the array this will work:
function checkEvenValues($text)
{
$skip = array(true, false);
// set $iskp to 0 if you want the first element to be counted as even; else, set it to 1
$iskp = 0;
foreach ($text as $idx=>$val)
{
$skp = 1 - $skp;
if ($skip[$iskp]) continue;
if($_SESSION['name'] == $text[$i]) return (true);
}
return (false);
}
function checkEvenValues($text)
{
if($_SESSION['name'] === $text[1]) return true;
for($i = 2; $i < count($text); $i += 2)
{
if($_SESSION['name'] === $text[$i])
return true;
}
}
Presuming that your keys are the same as the numbers in your values ([0] => 'info0') etc, you can use something like this combining some PHP array functions to filter down to only even keys (including 1), then a strict in_array() check to determine if it's there:
function compareEvens($text, $compare) {
// swap keys for values (back again)
$evens = array_flip(
// apply custom filter function
array_filter(
// swap keys for values
array_flip($text),
// return if its even OR its one
function($key) {
return $key % 2 === 0 || $key === 1;
}
)
);
return in_array($compare, $evens, true);
}
Example:
$text = array("info0", "info1", "info2", "info3");
var_dump(compareEvens($text, 'info2')); // true
var_dump(compareEvens($text, 'info3')); // false
Docs:
array_flip()
array_filter()
in_array()

Something wrong with my second else statement?

<?php
$check = array ("85.49.","85.62.");
foreach($check as $var) {
if (ereg($var, $_SERVER['REMOTE_ADDR'])) {
$intruder = 0;
}
else {
$intruder = 1;
}
if ($intruder = 0);
echo 'bugger off';
}
else{
echo 'welcome';
}
?>
What could be wrong with my second else? Dreamweaver red flags it and my server says error. All I want to do is get it to behave one way or another if $intruder is 1 or 0.
if ($intruder = 0);
First, you have an extra semicolon, so the body of the if statement is empty.
Secondly, = is assignment, you need comparison: ==.
The structure is not clear, but probably the next problem is your loop, which will overwrite $intruder in each iteration, so at the end it will contain the result of the last comparison.
The problem you ask about is on this line:
if ($intruder = 0);
You should be using == to compare the values, not = which is for assignment. And you should have a curly brace { after that instead of a semicolon.
Also, all of the ereg* functions are deprecated and should not be used. They will eventually be removed from the language entirely. To check if a word contains another word, just use strpos.
Your logic is also wrong for what you appear to be doing. You need to not overwrite the values of $intruder in each iteration of the loop. Set it to 0 before the loop, set it to 1 if there's a match in the loop, then after the loop is complete you'll know if there was a match during any of the comparisons and can print the appropriate message.
$found = 0;
foreach ($check as $var) {
if (strpos($_SERVER['REMOTE_ADDR'], $var) === 0) {
$found= 1;
}
}
if ($found == 1) {
echo "You are in my list.";
} else {
echo "You are not in my list.";
}
?>
Change this:
if ($intruder = 0);
To this:
if ($intruder == 0) {
First error:
if ($intruder = 0);
fix it in this way:
if ($intruder == 0)
echo 'bugger off';
else
echo 'welcome';
Second error:
The use of ereg is deprecated. Replace it with preg_match(); http://www.php.net/manual/en/function.preg-match.php
Friend, please do not be offended, but I'd rather have asked "is there anything right in this code?"
<?php
$check = array ("85.49.","85.62.");
foreach($check as $var) {
// Here you use the deprecated ereg instead of preg_match or, better, strpos
// However, the regular expressions would be wrong - what if 192.85.49.3 comes by?
if (ereg($var, $_SERVER['REMOTE_ADDR'])) {
$intruder = 0;
}
else {
$intruder = 1;
}
// Here you do not close the foreach, so that the following code gets executed
// repeatedly
// Here you place a ; after the if, so the if body is empty and bugger off gets
// triggered always.
// Which changes little, since $intruder = 0 is an assignment (use == instead)
// (see note)
if ($intruder = 0);
echo 'bugger off';
}
// Anyway, logically "$intruder == 0" means "NOT an intruder", so you are actually
// telling friends to bugger off and welcome intruders :-)
else{
echo 'welcome';
}
?>
Note: it is maybe voodoo programming (I found it on Maguire's 'Writing Solid Code'), but I think you might get into the habit of checking values the other way:
if (0 == $intruder)
This way if you ever drop a = again, it will not create a new statement doing something you wouldn't want, but it will become a syntax error that makes itself immediately visible.
Anyway, the code for what you want should be:
<?php
$check = array ("85.49.","85.62.");
$matches = false;
foreach($check as $var)
{
if (0 === strpos($_SERVER['REMOTE_ADDR'], $var))
{
$matches = true;
// There is one match, no sense in checking further
break;
}
}
if ($matches)
{
// He is in our little list - tell him something
print "You match.";
}
?>
Simple yaar.Just edit:
if ($intruder == 0);
echo 'bugger off';
}
else{
echo 'welcome';
}

Categories