Variable is not an array PHP - 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;
}
}
}

Related

PHP: How to get last array element in one array

i am trying to create function to check if array element is the last array element in one array. Original array looks like:
array(1001,
1002,
array('exam'=>true, 'index'=>10),
1003,
1004,
1005,
array('exam'=>true, 'index'=>20),
1006,
1007,
array('exam'=>true, 'index'=>30),
1008,
1009
)
I this case to prove if "array('exam'=>true, 'index'=>30)" is the last.
I have index position of that element, but I do not know how to check if that is the last array element.
function is_last_exam_in_survey($array, $exam_position) {
foreach($array as $element) {
if(!is_numeric($element) {
// check if that is the last array element in array
//return true;
} else {
// return false;
}
}
}
I would be grateful for any advice:)
function get_last_exam_in_survey($array) {
$last = null;
foreach($array as $element) {
if(is_array($element) && !empty($element['exam'])) {
$last = $element;
}
}
return $last;
}
function is_last_exam_in_survey($array, $exam_position) {
$last_exam = get_last_exam_in_survey($array);
return !empty($last_exam) && ($last_exam['index']==$exam_position);
}
I think this would be the quickest solution:
function is_last_exam_in_survey($array, $exam_position) {
$last_index = array_key_last( $array );
if( $exam_position == $last_index ){
return true;
}else{
return false;
}
}
You can still change the conditional statement if you are trying to compare values from the last element, for example:
if( isset($last_index['index']) && $exam_position == $last_index['index'] ){
Also, if you want to get the latest array value instead of key, you could use this:
$last_index = end( $array );
I would reverse the array, and look for the first element. Something like:
function is_last_exam_in_survey($array, $exam_position) {
foreach(array_reverse($array) as $element) {
if(!is_numeric($element) {
return $element['index'] === $exam_position;
}
}
return false;
}
Seems like the most efficient and simplest solution to me.
this solution avoid loop. at first we find out the last index of array.Then we use is_array() function for check the last element is array or not.
function get_last_exam_in_survey(array $arr)
{
$lastOfset = count($arr) - 1;
if(is_array($arr[$lastOfset])){
return true;
}else{
return false;
}
}
I think you can use array_column function to do that
function is_last_exam_in_survey($array,$exam_position){
$ac = array_column($array, 'index'); // return array(10,20,30)
$la = $ac[count($ac) - 1]; // 30
foreach ($array as $element) {
if (!is_numeric($element)) {
// check if $element['index'] === 30
if($element['index'] === $la){
return true;
}
}
}
}
How about using array_slice to extract the values in the array that are after the position you are looking at, then array_filter to remove any values that are not arrays. If there are any values left, then the entry you are looking at is not the last array entry in the array.
This may not be very efficient if you are calling it a lot of times with a large array. It may be better to rethink the way the data is stored or loaded into the array.
function is_last_exam_in_survey($array, $exam_position)
{
return isset($array[$exam_position])
&& is_array($array[$exam_position])
&& !array_filter(array_slice($array, $exam_position + 1), 'is_array');
}

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

Filtering a Multidimensional Array based of another array

I'm creating a PHP class that manipulates csv files.
As part of the class I have a function that allows the data to be filtered showOnlyWhere. However I get this error Invalid argument supplied for foreach() on line 331 (the line with the foreach statement). I tried adding global $arr; but that didn't work. How would i fix it?
$this -> rows is a multi-dimensional array that contains all the csv data.
$arr is in the format:
$key=>$val array(
$key = Column Name
$val = value that column should contain
)
Below is the showOnlyWhere function
function showOnlyWhere($arr)
{
if($this->showOnlyWhere == true){
$rows = $this->filteredRows;
}
else{
$rows = $this->rows;
}
$filter = function ($item){
global $arr; // didn't work
foreach($arr as $chkCol => $chkVal){
if ($item[$arr[$chkCol]] != $chkVal ){
return false;
break(3);
}
}
return true;
};
$this->filteredRows = array_filter($rows,$filter);
$this->showOnlyWhere = true;
}
I think the error might have something to do with the Anonymous function - but I'm not really sure.
instead of using global $arr you can make $arr available to the anonymous function via use
$filter = function ($item) use ($arr) {
//global $arr; // didn't work
foreach($arr as $chkCol => $chkVal){
if ($item[$arr[$chkCol]] != $chkVal ){
return false;
}
}
return true;
};
Also, I noticed that you are assigning $rows = $this->filteredRows; before you populate $this->filteredRows. I'm not sure if that's intentional?
Format for your $arr is wrong.
this is wrong:
$key=>$val array(
$key = Column Name
$val = value that column should contain
)
You cannot supply class objects to foreach, it should be a valid array.
It should be like this:
$arr=array(
$key => 'Column Name',
$val = 'value that column should contain'
);
So first convert your object to a valid array.

Finding for string in an Array

My problem is basically, I will be trying to get data from a table called, 'rank' and it will have data formatted like, "1,2,3,4,5" etc to grant permissions. So Basically I am trying to make it an array and find if one number is there in the array. Basically making it an array is not working. How would I get this done? Here is my code below:
<?php
function rankCheck($rank) {
$ranks = "1,2,3,4,5";
print_r($uRanks = array($ranks));
if(in_array($rank, $uRanks)) {
return true;
} else {
return false;
}
}
if(rankCheck(5) == true) { echo "Hello"; } else { echo "What?"; }
?>
This code returns false, while it should return true. This is just a basic algorithm.
The print_r Display:
Array ( [0] => 1,2,3,4,5 )
If you know for sure your delimiter is a comma, try this:
$ranks = explode(',',$rank);
where $rank is your string.
That's simple, you explode the $ranks variable by comma ,:
$ranks = "1,2,3,4,5";
$uRanks = explode(',',$ranks);
//$uRanks would now be array(1,2,3,4,5);
if(in_array($rank, $uRanks)) {
//..rest of your code
You should:
$uRanks = explode(',', $ranks);
instead of:
$uRanks = array($ranks);
to make this as array.
Problem solved. I used the explode function instead like this:
<?php
function rankCheck($rank) {
$ranks = "1,2,3,4,5";
print_r($uRanks = explode(',', $ranks));
if(in_array($rank, $uRanks)) {
return true;
} else {
return false;
}
}
if(rankCheck(5) == true) { echo "Hello"; } else { echo "What?"; }
?>

How to check if all values in multidimensional array are empty

I have a form posting a multidimensional array to my PHP script, I need to know if all the values in the array are empty or not.
Here is my array:
$array[] = array('a'=>'',
'b'=>array('x'=>''),
'c'=>array('y'=>array('1'=>'')),
'd'=>'');
I tried using array_reduce(), but it's just returning an array:
echo array_reduce($array, "em");
function em($a,$b){
return $a.$b;
}
Any ideas?
I noticed this has been hanging around for a while, this is a custom function that works quite well.
function emptyArray($array) {
$empty = TRUE;
if (is_array($array)) {
foreach ($array as $value) {
if (!emptyArray($value)) {
$empty = FALSE;
}
}
}
elseif (!empty($array)) {
$empty = FALSE;
}
return $empty;
}
if all items in the array is empty then the function will return true, but if one item in the array is not empty then the function will return false.
Usage:
if (emptyArray($ARRAYNAME)) {
echo 'This array is empty';
}
else {
echo 'This array is not empty';
}

Categories