how to use comparison in php - 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

Related

How to start a foreach loop with a specific value in PHP?

I need to start a for each loop at certain value, ex foreach($somedata as $data) Here I want to start doing some stuff only when the value of that data is "something"
I want to start doing something only after a specific value.
foreach($somedata as $data){
if($data == 'Something'){
//start processing, ignore all the before elements.
}
}
I tried break continue nothing seems to work as I wanted
For clarity, it's probably better to pre-process your array before looping over it. That way the logic inside your loop can purely focus on what it's supposed to do.
$arr = ['foo', 'something', 'bar'];
$toProcess = array_slice($arr, array_search('something', $arr));
foreach ($toProcess as $element) {
echo $element, PHP_EOL;
}
outputs
something
bar
How about using a indicator variable to achieve this.
$starter = 0;
foreach($somedata as $data){
if($data == 'Something'){
$starter = 1;
}
if(starter == 1){
//start processing, ignore all the before elements.
}
}
You'll need to keep a flag whether you have already encountered the desired value or not:
$skip = true;
foreach (... as $data) {
if ($data == 'something') {
$skip = false;
}
if ($skip) {
continue;
}
// do something
}
$skip = true;
foreach($somedata as $data){
if($data == 'Something'){
$skip = false;
}
if($skip) {
continue;
}
//start processing, ignore all before $skip == false.
}
If you want to process the values only from the moment you identify one value, then you can use a flag :
$flag = false;
foreach($somedata as $data){
if($flag OR $data == 'Something'){
$flag = true;
// processing some stuff
}
}
Once the flag is reset to true, whatever the current value is, the content of your if will be executed.

Variable is not an array PHP

when i try use in_array function in php for the second time for same array variable i got the following error saying:
in_array() expects parameter 2 to be array, string given in
when i wrap the function in condition is_array, it returns false, i already print the variable using print_r and its showing array structure, here's the code:
$chosenCour = array();
$chosenServ = array();
foreach ($preferences as $preference) {
if(!in_array($preference['courier'],$chosenCour)){
$chosenCour[] = $preference['courier'];
}
if(!in_array($preference['courier_service'],$chosenServ)){
$chosenServ[]= $preference['courier_service'];
}
}
foreach ($couriers as $courier) {
$courCond = false;
if(is_array($chosenCour)){
if(in_array($courier['courier_id'],$chosenCour)){
$courCond = true;
}
}
}
Check the additional condition for non empty array
foreach ($couriers as $courier) {
$courCond = false;
if(is_array($chosenCour) && count($chosenCour) > 0){
if(in_array($courier['courier_id'],$chosenCour)){
$courCond = true;
}
}
}

if condition fails while checking json array values

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";
}
?>

How to check each value in an array is empty?

If I have an array:
$nav = array($nav_1, $nav_2, $nav_3);
and want to check if they are empty with a loop (the real array is much bigger), so that it checks each variable separately, how do I do it?
I want something like this;
$count = 0;
while(count < 3){
if(empty($nav[$count])) //the loops should go through each value (nav[0], nav[1] etc.)
//do something
$count = $count+1;
}else{
//do something
$count = $count+1;
}
}
Pretty straight-forward with a foreach loop:
$count = 0;
foreach ($nav as $value) {
if (empty($value)) {
// empty
$count++;
} else {
// not empty
}
}
echo 'There were total ', $count, ' empty elements';
If you're trying to check if all the values are empty, then use array_filter():
if (!array_filter($nav)) {
// all values are empty
}
With the following code you can check if all variables are empty in your array. Is this what you are looking for?
$eachVarEmpty = true;
foreach($nav as $item){
// if not empty set $eachVarEmpty to false and go break of the loop
if(!empty(trim($item))){
$eachVarEmpty = false;
// go out the loop
break;
}
}
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);

Data Not Being Parsed Correctly

I have a simple data format that goes as follows:
stuff/stuff/stuff
An example would be:
data/test/hello/hello2
In order to retrieve a certain piece of data, one would use my parser, which tries to do the following:
In data/test/hello/hello2
You want to retrieve the data under data/test (which is hello). My parser's code is below:
function getData($data, $pattern)
{
$info = false;
$dataLineArray = explode("\n", $data);
foreach($dataLineArray as &$line)
{
if (strpos($line,$pattern) !== false) {
$lineArray = explode("/", $line);
$patternArray = explode("/", $pattern);
$iteration = 0;
foreach($lineArray as &$lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
else
{
$info = $lineData;
}
}
}
}
return $info;
}
However, it always seems to return the last item, which in this case is hello2:
echo getData("data/test/hello/hello2", "data/test");
Gives Me;
hello2
What am I doing wrong?
If you want the first element after the pattern, put break in the loop:
foreach($lineArray as $lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
elseif ($iteration == count($patternArray))
{
$info = $lineData;
break;
}
}
I also check $iteration == count($patternArray) so that it won't return intermediate elements, e.g.
/data/foo/test/hello/hello2
will return hello rather than foo.
P.S. There doesn't seem to be any reason to use references instead of ordinary variables in your loops, since you never assign to the reference variables.

Categories