skipping through foreach with multiple conditions - php

I'm trying to get my foreach to skip certain children in the xml based on one of the childrens values. The first code works for skipping just 1 but I want to skip a lot. The second code won't skip any of them.
<?php
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
foreach($gamespage->games->game as $game)
{
$gid = $game->appID;
if ($gid != 65920) {
} }
second code (not skipping any):
<?php
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
foreach($gamespage->games->game as $game)
{
$gid = $game->appID;
if ($gid != 65920 || $gid != 40940 || $gid != 50110 || $gid != 8990) {
} }

You need to use && instead of ||
Or even better
if (!in_array($gid, array(65920, 40940, ...)))

Related

How to exclude a parameter within an if statement?

I'm trying to create somewhat of a fuzzy search with PHP. Consider the following pseudo code/scenario below.
Take these $_POSTed values:
name
price
location
age
And I have an array of items (lets assume cars), of which each item contains the following properties:
name
price
location
age
So in my function, I use an if() within a foreach() to check if any of the posted data matches with an item and if it does, echo the item.
function search() {
$items = array(...);
$name = $_POST['name'];
$price = $_POST['price'];
$location = $_POST['location'];
$age = $_POST['age'];
foreach($items as $item) {
if(
$item['name'] == $name &&
$item['price'] == $price &&
$item['location'] == $location &&
$item['age'] == $age
){
echo json_encode($item);
}
}
}
The issue is that not every posted value is filled in, so for example $name could be empty i.e. $name = ''.
Question: How can I exclude any of the items in the if() statement if the initial $_posted key is empty without creating an if() inception type scenario? I considered using || but I'm pretty sure that wouldn't be the same as excluding a comparison all together. A
You can achieve that by taking advantage of PHP's lazy interpreter:
if(
(!$name || ($name && $item['name'] == $name)) &&
(!$price || ($price && $item['price'] == $price)) &&
(!$location || ($location && $item['location'] == $location)) &&
(!$age || ($age && $item['age'] == $age))
){
echo json_encode($item);
}
This will first check that each variable is not null, nor empty. (How exactly does if($variable) work?)
Also look at Does PHP have short-circuit evaluation?

Compare two json file with empty value

I have two json file, and need to sync them, if changes found, below is my json file,
is parent(P) and
another one
is child(C),
Here is my code :
foreach ($localJson->PushNotification as $key => $data ) {
foreach ($this->news as $news ) {
if($news->pushMessageId == $data->pushMessageId){
if($news->Image != "" && $news->Image != $data->Image){
echo "new image found <br />";
}
if($news->documentFile != "" && $news->documentFile != $data->documentFile){
echo "new documentFile found <br />";
}
if($news->categoryIcon != "" && $news->categoryIcon != $data->categoryIcon){
echo "new categoryIcon found <br />";
}
}
}
}
The Problem is everytime when it loops, it doesent discard previous loops value, if current found to be empty
For Ex: 1st loop 1653 pushMessageId compares pdf and updates in child, but for next pushMessageId again it takes same pdf to compare, rather then taking empty field.
I have check your code , its look a simple logical condition and need to update current objects new value.
foreach ($localJson->PushNotification as $key => $data ) {
foreach ($this->news as $news ) {
if($news->pushMessageId == $data->pushMessageId){
if($news->Image != "" && $news->Image != $data->Image){
$data->Image = $news->Image;
}
if($news->documentFile != "" && $news->documentFile != $data->documentFile){
$data->documentFile = $news->documentFile;
}
if($news->categoryIcon != "" && $news->categoryIcon != $data->categoryIcon){
$data->categoryIcon = $news->categoryIcon;
}
}
}
}
I hope this solution may work for you.

Yahtzee Php Code 3 of a Kind

if($_SESSION['valueofdie1'] != 0 && $_SESSION['valueofdie2'] != 0 && $_SESSION['valueofdie3'] != 0 && $_SESSION['valueofdie4'] != 0 && $_SESSION['valueofdie5'] != 0)
{
if((($_SESSION['valueofdie1'] == $_SESSION['valueofdie2']) && ($_SESSION['valueofdie2'] == $_SESSION['valueofdie3']||$_SESSION['valueofdie4']||$_SESSION['valueofdie5'])) || (($_SESSION['valueofdie1'] == $_SESSION['valueofdie3']) && ($_SESSION['valueofdie3'] == $_SESSION['valueofdie4']||$_SESSION['valueofdie5'])) || (($_SESSION['valueofdie1'] == $_SESSION['valueofdie4']) && ($_SESSION['valueofdie4'] == $_SESSION['valueofdie5']))
|| (($_SESSION['valueofdie2'] == $_SESSION['valueofdie3']) && ($_SESSION['valueofdie3'] == $_SESSION['valueofdie4']||$_SESSION['valueofdie5'])) || (($_SESSION['valueofdie2'] == $_SESSION['valueofdie4']) && ($_SESSION['valueofdie4'] == $_SESSION['valueofdie5']))
|| (($_SESSION['valueofdie3'] == $_SESSION['valueofdie4']) && ($_SESSION['valueofdie4'] == $_SESSION['valueofdie5'])))
{
if($_POST['choose'] == 'choose 3oaK')
{
$_SESSION['g'] = 5;
$_SESSION['scoretkind'] = $_SESSION['valueofdie1'] + $_SESSION['valueofdie2'] + $_SESSION['valueofdie3'] + $_SESSION['valueofdie4'] + $_SESSION['valueofdie5'];
unset($_SESSION['3oaKBut']);
echo '<input type="hidden" name="choose" value="Clear" onLoad="form.submit();">';
$_POST['sub'] = 'reset';
$_POST['choose'] = '';
}
if(empty($_SESSION['g']))
{
$_SESSION['3oaKBut'] = '<input type="submit" name="choose" value="choose 3oaK">';
echo $_SESSION['3oaKBut'];
}
}
}
if($_SESSION['g'] == 5)
{
echo $_SESSION['scoretkind'];
}
So here is the code we have. We are trying to check if 3 of the 5 die values are equal. If they are equal we echo out a button that allows the user to choose to score his 3 of a kind, which is the total of all of the dice. Everything works except in some cases the 3 of a kind button would echo out when there isnt a 3 of a kind. Halp PLS
I'm sorry I didn't answer your question by actually solving your bug, but I think your code is hard to read and your approach makes it cumbersome to program all the rules.
General advice: Put $_SESSION['valueofdie1'] and the other dice into an array of values. That's much easier to work with. After that, it should be pretty easy to check how many times each value occurs. Even when you keep your approach, you could make variables like $die1, which is already a lot shorter and more readable than $_SESSION['valueofdie1'].
But with an array, you could roughly start like this:
// Put all dice into an array.
$dice = array(
$_SESSION['valueofdie1'],
$_SESSION['valueofdie2'],
etc.... );
// Count how many times each die is rolled.
$diceCount = array();
foreach($dice as $die) {
$count = 0;
if (isset($diceCount[$die])) {
$count = $diceCount[$die];
}
$diceCount[$die] = $count + 1;
}
// Check possible results simply by looking at those counts.
// If one die value is rolled 5 times, it's Yahtzee...
if (array_search(5, $diceCount) !== false) {
echo 'Yahtzee!';
}
if (array_search(4, $diceCount) !== false) {
echo 'Four of a kind';
}
// Full house takes two types.
if (array_search(3, $diceCount) !== false && array_search(2, $diceCount) !== false) {
echo 'Full house';
}
for ($diceCount as $die => $count) {
echo "$count times $die";
}
... etc ...
You'll need to expand this list, and take some other rules into account. After all, a Yahtzee could also count as a Four of a Kind. But by checking all those rules, you can generate a new array of possible combinations, which you can check against the previously chosen options. And the outcome of that determines which options the player can choose.

Using if (!empty) on multiple variables but displaying content if one isn't empty

I'm using the following
if (!empty($data['var_1'])
&& !empty($data['var_2'])
&& !empty($data['var_3'])
&& !empty($data['var_4'])
&& !empty($data['var_5'])
&& !empty($data['var_6'])
&& !empty($data['var_7'])
&& !empty($data['var_8'])
&& !empty($data['var_9'])) {
//BLOCK HERE
}
Basically, what I'm trying to achieve is if all of the variables are empty, hide the block. If 8 or less are empty, display the block.
Where am I going wrong?
You want || not &&. This will display the block only if they are all not empty. I think there is probably a nicer way to do this, though, like array_filter.
Well, you could just use a loop and an $isok variable:
$isok = false;
for($i=1; $i<10; $i++) {
if( !empty($data['var_'.$i])) {
$isok = true;
break; // no need to continue looping
}
}
if( $isok) {
// BLOCK HERE
}
This is easier to edit too, in case you change the var_ part or want a different range of numbers.
You can also try
$data = array_filter($data); // remove all empty value form array
if (count($data)) {
// do your thing
}
The code you wrote will display the block if ALL of the variables aren't empty. If you want it to be displayed when ANY of the variable isn't empty, use OR instead of AND by replacing the && by ||.
<?php
if (!empty($data['var_1']) || !empty($data['var_2']) || !empty($data['var_3']) || !empty($data['var_4']) || !empty($data['var_5']) || !empty($data['var_6']) || !empty($data['var_7']) || !empty($data['var_8']) || !empty($data['var_9'])) {
//BLOCK HERE
}
You can use array_values() for that:
if ( count(array_values($data)) ) {
//BLOCK HERE
}
Replace && (AND) with || (OR)
if (!empty($data['var_1'])
|| !empty($data['var_2'])
|| !empty($data['var_3'])
|| !empty($data['var_4'])
|| !empty($data['var_5'])
|| !empty($data['var_6'])
|| !empty($data['var_7'])
|| !empty($data['var_8'])
|| !empty($data['var_9'])) {
//BLOCK HERE
}
if (empty(array_values($data))) { /* will return you true if all variables are empty*/}

how to appear form element only if there is no "%" sign in php

I have a form with many form elements that are not allways populated with data, depending on type of product. If I want to print one row - record from mysql db, I want to avoid print column with empty container for data or if I put "%" sign in it. Does anyone has an idea how to do that? Examples are welcome!
if ($yourValue != '' && strpos($yourValue, '%') === FALSE)
{
// print empty container
}
...but how do you handle the case where the original database value contains already % and therefore should be displayed (see Bracketworks's comment)?
You can just check against null or a blank string to see if the column is empty and use strpos to see if '%' appears in it. Only print the column data if the conditions are satisfied:
<?php if (!is_null($row['column']) && $row['column'] != '' && false === strpos($row['column'], '%')) : ?>
<?php echo $row['column']; ?>
<?php endif; ?>
Or in raw php:
if (!is_null($row['column']) && $row['column'] != '' && false === strpos($row['column'], '%')) {
echo $row['column'];
}
$query = "SELECT * FROM TABLE WHERE ID = 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
foreach ($row as $key => $value) {
if ($value != "" && strpos($value, '%') === false) {
//Do your output here...
}
}
}

Categories