array_key_exists in a foreach - php

Hi There I am running this code currently,
<?php foreach($search_results as $rslt) : ?>
<?
$code = $rslt['code'];
if(array_key_exists($code, $short_list)) {
$set = "set";
}
?>
<div class="row <? echo $set;?>"></div>
What I am trying to achieve is that if the array equals the $rslt['code'] then give the div the class of set otherwise don't the array I checking against looks like this,
Array
(
[849650047] => Y
[849652539] => Y
[849652774] => Y
[849656557] => Y
[849652014] => Y
)
However every time I loop all my divs get set with the 'set' class? It should only be where the array_key equals the current $code

Well, they are all set, because you're never initializing the $set variable:
<?php foreach($search_results as $rslt) : ?>
<?
$set = '';
$code = $rslt['code'];
if(array_key_exists($code, $short_list)) {
$set = "set";
}
?>
<div class="row <? echo $set;?>"></div>
Also, just use isset() instead of array_key_exists (it's more efficient, and less wordy):
if(isset($short_list[$code])) {
$set = "set";
}

just add unset($set); at end of your loop. Or you can do something like...
<?php foreach($search_results as $rslt) : ?>
<div class="row <? print array_key_exists($rslt['code'], $short_list)? 'set':''; ?>"></div>
<?php endforeach; ?>

Avoid the alternate control structure syntax in PHP. It's ugly and makes your code more difficult to maintain in the long run. Also try to avoid excessive context switching with <?php ?>; it makes your logic needlessly difficult to follow.
<?php
foreach ($search_results as $result) {
$set = isset($short_list[$result['code']]) ? ' set' : '';
echo "<div class=\"row$set\"></div>";
}
Note that isset() will return false if the key exists in the array, but its value is null. Something to watch out for if you want the "set" class applied even if the value of $short_list[$result['code']] is null.

Related

Automatization of a conditional function through the use of an array to test postdata variables

I have some problems to make the following automatization:
I get from a form a lot of variables such as $a and $b.
I would like to automatize a conditional test depending on the variables I obtain.
$test = array('a','b');
for($i=0;$i<sizeof($test);$i++)
For the 1st variable a, the working code is:
if ( $postdata->a !=${$test[$i]}){echo "different";} else {echo "same";}
For the 2nd variable b, the working code is:
if ( $postdata->b !=${$test[$i]}){echo "different";} else {echo "same";}
I would like to automatize it thanks to the array like this:
if ( $postdata->$test[$i] !=${$test[$i]}){echo "different";} else {echo "same";}
but $postdata->$test[$i] doesn't work, even echo $test[$i] gives 'a' and 'b'.
I tried several "writing" but I couldn't solve it.
Thank you for your help.
Instead of making your code too complex with $test[$i] and for loop instead use foreach. Hope this will work fine.
Try this code snippet here contains sample input
<?php
ini_set('display_errors', 1);
$test=array('a','b');
foreach($test as $i => $value)
{
if ($postdata->{$value} != ${$value})
{
echo "different";
}
else
{
echo "same";
}
}

Is this the correct way of checking empty array?

I want to check if array is empty or not, i wrote few lines of code for it
if(array() == $myArray){
echo "Array";
}
or
if(array() === $myArray){
echo "Array";
}
I'm confused which one to use, as the second condition also checks type. But i think in the case of array we don't need to check their type.
Please anybody can suggest me which one to use.
you can check it by using empty() function like below
<?php
if(empty($myArray)) {
//condition
}
?>
if (! count($myArray)) {
// array is empty
}
Let php do its thing and check for booleans.
Use empty:
if (empty($myArray)) {
...
}
Try this :
<?php
$array = array();
if(empty($array))
{
echo "empty";
} else
{
echo "some thing!";
}
?>
It's always better to check first whether it is array or not and then it is empty or not. I always use like this because whenever I check only empty condition somewhere I don't get the expected result
if( is_array($myArray) and !empty($myArray) ){
.....
.....
}
<?php
if(empty($yourarry)){
}
OR
if(isset($yourarry)){
}
OR
if(count($yourarry)==0){
}
It depends:
Use count==0 if your array could also be an object implementing Countable
Use empty otherwise
array() == $myArray is unreadable, you should avoid it. You can see the difference between count and empty here.

lost var in php

I am fairly new to PHP and Yii, and the problem that I am not nor as the question in google, so the only thing I can think of is to ask the question to this list that I have solved many problems.
The issue is as follows: in the code that I attached, I read several records that I keep in array and after the process.
Well, if you look at the debug entries in foreach in he first, all goes well and the variable $items is loaded, but when I get to the second debug $items variable has the correct number of elements, but the elements are empty : count ($items) = 2 but $items[0] and $items[1] are null
$idiomas=CListaMidiomas::model()->findAll();
$items=array();
$nombre=array();
$a=0;
foreach ($idiomas as $idioma){
$nombre[$a]=$idioma->sIdioma;
$items[$a]=TblCategoriastexto::model()->findAll(
array('condition'=>'id='.$data->id.' AND idIdioma='.$idioma->id_idioma));
echo "<br>---AAAAAAAAAAA--".$a."-----------<br>";
CVarDumper::dump($items); //in this moment is correct
if (empty($items[$a]) ||$items[$a]==null ){ // not enter because $items have content
$items[$a]=new TblCategoriastexto();
$items[$a]->idIdioma=$idioma->id_idioma;
}
$a++;
}
echo ">>>>>>>>>>>>>>>".count($items) ; //<<<<<<<<<<present 2
CVarDumper::dump($items); // but in this moment t0 2 are null
for ($a=0;$a<count($items) ;$a++){
echo "<b>".CHtml::encode($nombre[$a]).":</b>";
$out="";
$item=$items[$a];
echo "<br>-----".$a."-----------<br>";
CVarDumper::dump($items[$a]);<<<<<<<<<<<<<<<<<<<<<<<<null
for ($b=1;$b<=20;$b++){
$campo="tc".$b;
$out.=$items[$a]->$campo . ",";<<<<<<<<<<<<<<<<error
}
echo CHtml::encode($out);
echo"<br>";
}
This line: if (empty($items[$a]) ||$items[$a]=null ){ will always assign $items[$a] to null.
To compare values, use the comparison (for equality) operator, == instead of the assignment operator =.
Try changing this line:
if(isset($items[$a]->$campo)) {
$out.=$items[$a]->$campo . ",";
}

Using Same If Else Statement Multiple Times

I'm doing this...
<?php $term = ucfirst($_GET['term']);?>
And doing this multiple times on the page:
<?php if (empty($term)) echo 'X'; else echo $term; ?>
Is there a better way to go about this?
You can specify the placeholder value when you first assign the value:
<?php $term = ucfirst($_GET['term']) or $term = "X"; ?>
(Works because the OR has lower precedence than the assignment.)
Then just print that variable henceforth:
<?= $term ?>
It will contain either the input value, or your X.
ternary operator :
$term = (empty(ucfirst($_GET['term']))) ? echo 'X' : $_GET['term'];
Declare a function
function doTerm()
{
$term = ucfirst($_GET['term']);
if (empty($term)) echo 'X'; else echo $term;
}
so you can call it like
doTerm();
whenever you need it to test and echo.
<?php
$term = isset($_GET['term']) ? ucfirst($_GET['term']) : 'X';
echo $term;
//...
?>
If you don't need it anywhere else than you could make it even shorter :-)
echo (isset($_GET['term']) ? ucfirst($_GET['term']) : 'X');
Ternary syntax can work easily here:
Using short hand tags:
<?=empty($term) ? 'X' : $term ?>
or long hand:
<?php echo empty($term) ? 'X' : $term ?>
you can use Conditional Operator like
echo ($term!=null)? 'x' : $term;

What is meant by this php statement

Hello I have read following php statement from a blog but I am unable to understand its meaning. Is it treated as if condition or any thing else? Statement is
<?= ($name== 'abc' || $name== 'def' || $name== 'press') ? 'inner-pagehead' : ''; ?>
You can read this as:
if($name=='abc' || $name=='def' || $name=='press') {
echo 'inner-pagehead';
} else {
echo '';
}
The <?= is the echo() shortcut syntax, then the (test)?true:false; is a ternary operation
It is saying that if $name is any one of those 3 values ("abc","def", or "press"), then display the text "inner-pagehead". Otherwise, don't display anything.
This is what I would call a poorly written Ternary condition. it basically echos 'inner-pagehead' if the $name variable matches any of the three conditions. I would have done it like this:
<?php
echo in_array($name, array('abc', 'def', 'press')) ? 'inner-pagehead' : '';
?>
Or, even better:
// somewhere not in the view template
$content = in_array($name, array('abc', 'def', 'press')) ? 'inner-pagehead' : '';
// later, in the view template
<?php echo $content; ?>

Categories