PHP in_array() returning false always [duplicate] - php

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
I'm trying to check if a value is in a array but it's always returning false. I've tried to fix this in quite a few different ways but none worked.
I have this file which I used require_once '../path/'; to add it to my current script. It is a JSON that was converted to PHP nested arrays.
This is the function that is always returning false. I did a lot of testing using echo and everything looks fine with $states_json and the array $cities.
If anyone could help me with this situation I would be apprciated.
EDIT: I'm calling this function with validateInstCity("RS", "Porto Alegre") so it was supposed to return true. After some more testing, I found out that the problem is that $states_json is NULL within the function. The strange part is that I used it inside others functions before without any problems. As you may see on the file, when using validateInstCity("RS", "Porto Alegre") $idx should be 22 and the function should return true.
function validateInstCity($inst_province = null, $inst_city = null) {
if (empty($inst_province) ||
empty($inst_city)) {
}
$idx;
for ($i=0; $i < count($states_json); $i++) {
if ($states_json[$i]['sigla'] == $inst_province) {
$idx = $i;
break;
}
}
$cities= array();
for ($i=0; $i < count($states_json[$idx]['cidades']); $i++) {
array_push($cities, $states_json[$idx]['cidades'][$i]);
}
if (in_array($inst_city, $cities, false)) {
return true;
} else {
return false;
}
}

Related

Passing array reference to function PHP [duplicate]

This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 1 year ago.
I'm fairly new to PHP. I'm trying to filter out an array of items that contain a specific string. In order to then push those items to array, I need to pass the array to the function as a reference (or so my research has told me) however I can't seem to get it to work, any ideas? Thanks all.
$filteredS3Results = array();
function filterResults($var, &$filteredS3Results) {
if (strpos($var, '008-20160916') !== false) {
array_push($filteredS3Results, $var);
};
};
array_filter($s3Results,"filterResults");
The callback function just receives one argument, the array element being tested. It should return a boolean value that indicates whether the element should be included in the filtered result.
$filteredS3Results = array_filter($s3Results, "filterResults");
function filterResults($var) {
return strpos($var, '008-21060916') !== false;
}

How to fix an "Creating default object from empty value in" error? [duplicate]

This question already has answers here:
Creating default object from empty value in PHP?
(18 answers)
Closed 4 years ago.
I am using PHP 5.6 and have the following code:
$page->adminNavi[$i]->active = _SITE == $file || _ACTIV_NAVI == $key ? true : false;
On the above line, I am receiving the following error:
Creating default object from empty value in
How can I fix this error?
The error is from this:
$page->adminNavi[$i]->active
Either $page isn't set or an object, or adminNavi isn't an array, or adminNavi[$i] doesn't exist, or isn't a stdClass.
Debug it!
var_dump($page->adminNavi); exit;
With luck, you'll get an array. In which case var dump array key $i and see what's in there.
UPDATE: okay so the var dump returns this
array(1) { [0]=> object(stdClass)#2 (1) { ["active"]=> bool(false) } }
How many times does $i change? If it's anything other than 0, that array key will not exist, but you immediately refer to it like it does, and since you treat it like a stdClass, it creates one on the fly but generates the warning.
To sum up, make sure $i exists by counting the array! If $i is set from a loop, then something like this:
for ($i = 0; $i <= count($page->adminNavi): $i++) {
// your code
}

What is the logic behind the isset() function in PHP? [duplicate]

This question already has answers here:
pass an argument that may not be set to a function, without throwing a notice
(3 answers)
Why check both isset() and !empty()
(10 answers)
Closed 4 years ago.
I accidentally experience this issue when I was writing code in one of my application.
$ar = [
'first' => 1,
'second' => 2,
......
];
when I tried to check that index in $array which doesn't exist
if(isset($ar['third']) && !empty($ar['third'])){
echo "Found";
}else{
echo "Not Found";
}
It worked without error as expected, but when I put this conditions in the common function and then checked
function sanitize($value){
if(isset($value) && !empty($value)){
return true;
}else{
return false;
}
}
if(sanitize($ar['third'])){
echo "Found";
}else{
echo "Not Found";
}
Above sample throws an exception undefined index error, can someone explain why this is causing the error.
$value is always set because it is declared as a function parameter so it always exists. So in this case using isset() is pointless.
function sanitize($value){ // <-- Variable is declared so it exists
// within the scope of this function
You are trying to refer to the $ar array at that the 'third' index before the isset/empty check is actually executed (as that is within the sanitise function).
PHP is therefore showing the error for the if(sanitize($ar['third'])){ line.

PHP | parse error T_DOUBLE_ARROW [duplicate]

This question already has answers here:
unexpected T_DOUBLE_ARROW [closed]
(2 answers)
Closed 6 years ago.
Hi i'm learning some basic php, and i'm having some a parse error. It says that the error is located on line 8(if($book=>$find)). What is wrong with line 8?
function getPrice($find)
{
$books = array ("java"=>299,"c"=>348,"php"=>267);
foreach ($books as $book=>$price)
{
if($book=>$find)
{
return $price;
break;
}
}
}
thank you in advance :D
Use == or === to compare change here
if($book == $find)
Also no need to write break after return here
return $price;
break;
By the way you can also write your code like this
<?php
function getPrice($find)
{
$books = array ("java"=>299,"c"=>348,"php"=>267);
if(isset($books[$find])){
return $books[$find];
}
return false;
}
echo getPrice("java");
?>
Check here : https://eval.in/592069
Your syntax:
if($book=>$find)
is incorrect.
From what I see, it seems like you want to find a book which matches $find.
Try this instead:
if ($book==$find)

Recursive function: echo works, return doesn't [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
The function aims at finding an item in a range of arrays, and then returning its key.
Problem is that the function doesn't return anything, whereas it would echo the expected result...
Here is my code:
function listArray($tb, $target){
foreach($tb as $key => $value){
if(is_array($value)){ // current value is an array to explore
$_SESSION['group'] = $key; // saving the key in case this array contains the searched item
listArray($value, $target);
}else {
if ($target == $value) { // current value is the matching item
return $_SESSION['group']; //Trying to return its key
break; // I'd like to close foreach as I don't need it anymore
}
}
}
}
By the way, an other little thing: I'm not used to recursive function, and I didn't find any other solution than using a session variable. But there might be a nicer way of doing it, as I don't use this session variable elsewhere...
You need a return before the recurring listArray call.
Thank about it ..
return;
break;
That break is never reached (I don't believe you can use break to exit a function in php anyway)
The second return returns from a recursive call. Let's say that this was not two separate functions:
function foon() {
barn();
}
function barn() {
return true;
}
foon has no return statement.
I finally bypassed the problem by storing my result in a $_SESSION variable.
So, no return anymore...
$_SESSION['item'][$target] = $_SESSION['group'];

Categories