Why does in_array() always return false? - php

Try this code:
You use the URL with the parameter id e.g index.php?id=value
This value will be pushed into the data array that is maintained within a session.
I expect this test to always return true. But it always returns false, why?
if (in_array($id, $_SESSION['data'])) {
echo "$id in array";
} else {
echo "$id not in array";
}
The full code:
<?php
session_start();
//uncomment when need to clear the data array.
//if (isset($_SESSION['data'])) {
// unset($_SESSION['data']);
// die;
//}
if (!isset($_SESSION['data'])) {
$_SESSION['data'] = [];
}
if (isset($_GET['id'])) {
$id = strval($_GET['id']);
if (!in_array($id, $_SESSION['data'])) {
$_SESSION['data'][$id] = "data_$id";
}
echo '<pre>';
print_r($_SESSION['data']);
echo '</pre>';
// Why does this always return false?
if (in_array($id, $_SESSION['data'])) {
echo "$id in array";
} else {
echo "$id not in array";
}
}?>

Try isset() function.
Example:-
if (isset($_SESSION['data'][$id])) {
echo "$id in array";
} else {
echo "$id not in array";
}

Related

How to store $_FILES superglobal variables in an array and loop through them to find a match in PHP?

I'm running if statements to identify each variable independently. My code is a bit messy and long but it works with no problem. I'd like to see if it is possible to use an array to store them and run a loop to see if there is a match, instead of using if statements.
PHP code...
if (move_uploaded_file($_FILES["index_deslizador_Cfile1"]["tmp_name"], $index_deslC1)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Cfile2"]["tmp_name"], $index_deslC2)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Cfile3"]["tmp_name"], $index_deslC3)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Cfile4"]["tmp_name"], $index_deslC4)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile1"]["tmp_name"], $index_deslM1)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile2"]["tmp_name"], $index_deslM2)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile3"]["tmp_name"], $index_deslM3)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else if (move_uploaded_file($_FILES["index_deslizador_Mfile4"]["tmp_name"], $index_deslM4)) {
echo "<script>window.open('../index.php','_self')</script>";
}
else {
echo "Sorry, there was an error uploading your file.";
}
I'm fairly new to PHP, so I may get scolded for this suggestion :)
If you could get $index_deslC# variables into an array, you might be able to do something like this:
$i = 1
$destination = array($index_deslC...
foreach($_FILES["index_deslizador_Mfile" . $i]["tmp_name"] as $filename) {
isset(move_uploaded_file($filename, $destination[$i]) ?
echo "<script>window.open('../index.php','_self')</script>" : echo '';
$i++;
}

Wrong output in php program

Following is my code here actually o/p should be hi..but it is giving no
<?php
$arr=array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$c='xyz,ccc';
if(in_array(isset($c) && $c,$arr))
{
echo 'hi';
}
else
{
echo 'no';
}
?>
output:hi
actual result should be 'no'.
Side note, this is bad code:
in_array(isset($weekendArr) && $weekendArr,$arr)
do it like
isset($weekendArr) && in_array($weekendArr,$arr)
and in_array is not strict so this
in_array(true,array('w','s'))
will be allways TRUE
do it with:
in_array(true,array('w','s'),true)
and you see.
And you can't check an array with an array the $needle be an STRING here.
The only solution is to do splitt your STRING into two values and then check two times for TRUE
$c='Sunday,Monday';
foreach(explode(',',$c) as $check){
if(in_array($c,$arr,true))
{
echo $check.' is in array';
}
else
{
echo $check.' is NOT in array';
}
}
Hope that helps a little.
<?php
$listDays=array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$day='Sunday'; //You cant test both days ! Just one value at a time
if(true === in_array($day, $listDays))
{
echo 'hi';
}
else
{
echo 'no';
}
?>
Or option two if you want to test different days
<?php
$listDays=array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$dayToTest='Sunday, Monday'; //Here we have multiple days
$tabTest = preg_split(',', $day); //split into an array
//Then test for each string in tabTest
foreach($tabTest as $string)
{
if(true === in_array($string, $listDays))
{
echo $string.' is OK';
}
else
{
echo 'no';
}
}
?>
Change your code to:
<?php
$arr=array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
$c='Sunday,Monday';
if(in_array(isset($c) && $c,$arr))
{
echo 'hi';
}
else
{
echo 'no';
}

How to Perform True False Comparison on Two different array values

I have two arrays:
$array_one = array(1=>6000,2=>500);
$array_two = array(1=>6500,2=>250);
I would like to compare the values with > or < like this:
if(6000 > 6500){
echo "ok";
}else{ echo "not allowed";}
if(500> 250){
echo "ok";
}else{ echo "not allowed";}
How can I perform this type of operation using a loop or something else?
You access array values using the square bracket notation [index], therefore you can simply reference the values using their index;
if($array_one[1] > $array_two[1]) {
echo "ok";
}
else {
echo "not allowed";
}
and then you can put that in a loop, like this;
for($i=1;$i<=count($array_one);$i++) {
if($array_one[$i] > $array_two[$i]) {
echo "ok";
}
else {
echo "not allowed";
}
}
Hope this helps.
Try the following:
<?php
foreach($array_one as $key => $value) {
if($value > $array_two[$key]) {
echo "OK";
} else {
echo "Not Allowed";
}
}
?>
Try this:
$array_one = array(1=>6000,2=>500);
$array_two = array(1=>6500,2=>250);
foreach($array_one as $k => $v)
{
if($v > $array_two[$k]){
echo "ok";
}else{ echo "not allowed";}
}

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

why can't array_search find the value if the code of the key is "gb2312"?

my questions:
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result = array_search("你",$state);echo $result;
}else
{
echo "No Exists";
}
i expect the result of "1", however the output is "No Exists", i don't know why the program can't get the value of the key "你".
array_search will search the given array by value. Try the following:
$state = array("你"=>1);
if(array_key_exists("你", $state)) {
echo $state["你"];
} else {
echo "No Exists";
}
// => 1
» demo
Hope below function will help.
<?php
$array = array('arr1'=>array('find_me'=>'yes you did.'));
function get_value_by_key($array,$key)
{
foreach($array as $k=>$each)
{
if($k==$key)
{
return $each;
}
if(is_array($each))
{
if($return = get_value_by_key($each,$key))
{
return $return;
}
}
}
}
echo get_value_by_key($array,'find_me');
?>
the encoding type of the show paper and the store paper is GB2312.
$state=array("你"=>1);
if(array_key_exists("你",$state))
{
$result1 = $state["你"];
echo $result1; // can get the value 111
}else
{
echo "No Exists";
}
the code above can be executed rightly. i can't show my problems accurately. Now i paste out my code , there is some questions.
<?php
$file = file("GB2312-HanZiBianMa.txt"); // file encoding type ANSI
foreach ($file as $line_num => $line)
{
list($no,$hex,$dec) = preg_split('[\t]',htmlspecialchars($line));;
$result[$hex] = $dec;
}
$result_2 = array_flip($result);
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}
foreach($result_2 as $k=>$each) //can get the value using the preg_match
{
if(preg_match('/你/', $k))
echo $k."\t".$each."<br/>";
}
?>
the format of GB2312-HanZiBianMa.txt is as follows:
1947 c4e3 你
1948 c4e4 匿
1949 c4e5 腻
1950 c4e6 逆
if your want to test the code , you can save the php code and save the GB2312.. file.
the question is:
why can't the following function get the right value ? the data comes from file and one stores together.
if(array_key_exists("你",$result_2)) // **can't find the value** 222
{
$state= $result_2["你"];
echo $state."<br/>";
}else
{
echo "No Exists<br/>";
}

Categories