PHP output only one value in for each - php

I'm having trouble with output in for each function in PHP (actually don't know how to set the code to do what I need). I'd like to output some text if every item in foreach is equal to some value. If I put
foreach($items as $item) {
if($item == 0){ echo "true"; }
}
I will get true for every item and I need to output true only if all items are equal to some value.
Thanks!

This is most likely due to PHP type juggling your values. Your values are probably not numeric so when you do a loose comparison (==) PHP converts them to integers. Strings that do not start with digits will become zero and your statement will be true.
To fix this use the === comparison operator. This will compare value and type. So unless a value is the integer zero it will be false.
if($item === 0){ echo "true"; }
If you are trying to see if all items are equal to some value this code will do this for you:
$equals = 0;
$filtered = array_filter($items, function ($var) use ($equals) {
return $var === $equals;
});
if (count(count($items) === count($filtered)) {
echo "true";
}

This peice of code work for most type of variables. See how it works in inline comment.
$count=0; // variable to count the matched words
foreach ($items as $item)
{
if($item == $somevalue)
{
$count++; // if any item match, count is plus by 1
}
}
if($count == count($items))
{
echo "true"; // if numbers of matched words are equal to the number of items
}
else
{
echo "false";
}
Hope it works , And sorry for any mistake

$ok = true;
foreach ($items as $item)
{
if ($item != 0)
{
$ok = false;
}
}
if ( $ok == true)
{
echo 'true';
}

$bool = 0;
foreach($items as $item) {
if($item == $unwantedValue)
{ $bool=1; break; }
}
if($bool==0)
echo 'true';

$equals=true;
foreach($items as $item) {
if($item!=0)
{
$equals=false;
break;
}
}
if($equals) {
echo 'true';
}

if you want to check the values is same with some value in variabel and print it use this
<?php
$target_check = 7;
$items = array(1, 4, 7, 10, 11);
foreach ($items as $key => $value) {
if ($value == 7) echo "the value you want is exist in index array of " . $key . '. <br> you can print this value use <br><br> echo $items[' . $key . '];';
}
?>
but if you just want to check the value is exist in array you can use in_array function.
<?php
$target_check = 2;
if (in_array($target_check, $items)) echo "value " . $target_check . 'found in $items';
else echo 'sorry... ' . $target_check . ' is not a part of of $items.';
?>

<?
$items=array(0,1,2,0,3,4);
foreach($items as $item) {
if($item == 0){ echo "true"; }
}
?>
your code work!
check the source of the $items array

Related

How to check values inside foreach loop are same or not

i have a foreach loop as
foreach ($age as $ages) {
echo $ages;
}
when run this code the result is
3
3
or
1
3
i want to check if values are same or not. For example
if (values are same) {
do something...
}
else {
do something...
}
i really couldn't find how to check values are same or not.
If you are checking to see if all values are identical just use array_unique() to remove duplicate values. Then check to see if the size of the remaining array is equal to 1:
$is_all_duplicates = count(array_unique($array)) === 1;
If any duplicates will trigger this condition, just use array_unique() to remove duplicate values and then compare the sizes of the two arrays. If they are not the same you had duplicate values:
$is_some_duplicates = count(array_unique($array)) < count($array);
If values are the same, then array_count_values will have one element only:
$a = [1,2,3,3];
$acv = array_count_values($a);
if (count($acv) == 1) {
echo 'values are the same';
} else {
echo 'values are NOT the same';
}
$a = [3,3,3];
$acv = array_count_values($a);
if (count($acv) == 1) {
echo 'values are the same';
} else {
echo 'values are NOT the same';
}
The fiddle.
But the most optimal solution is a simple loop with break on first value that is not equal to first of the array:
$a = [1,2,3,3];
$hasSameValues = true;
$firstElem = array_slice($a, 0, 1)[0];
foreach ($a as $el) {
if ($el != $firstElem) {
$hasSameValues = false;
break;
}
}
if ($hasSameValues) {
echo 'values are the same';
} else {
echo 'values are NOT the same';
}
echo PHP_EOL;
$a = [3,3,3];
$hasSameValues = true;
$firstElem = array_slice($a, 0, 1)[0];
foreach ($a as $el) {
if ($el != $firstElem) {
$hasSameValues = false;
break;
}
}
if ($hasSameValues) {
echo 'values are the same';
} else {
echo 'values are NOT the same';
}
Yet another fiddle.
You possible want to 'say' :)
foreach ($ages as $age) {
echo $age;
}
I understand that you want to check if only previous value is equal with actual value.
To check that write this:
$ages = [1,1,7,2,2,4,1,2];
foreach ($ages as $age) {
if(isset($temp) ? !($temp == $age) : true){
echo $age;
}
$temp = $age;
}
The result is: 172412
The code:
Check if variable $temp is set: isset($temp)
If it is set, check if it is NOT equal with last age value: !($temp == $age)
If the $temp isn't set, set true to run the code from if statement (echo the age)(is there for first run).

Add values to $_SESSION['name'] then Loop thru values

I'm using a $_SESSION variable to store error codes in an app I'm creating.
On my form processing page, i'm using the following code (as an example):
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
$_SESSION['site_msg'] = 18;
}
if(2 == 2) {
$_SESSION['site_msg'] = 21;
}
if(3 == 3) {
$_SESSION['site_msg'] = 20;
}
I'm hoping to use a function to get the values from the array to use elsewhere in my code.
function error_code() {
foreach($_SESSION['site_msg'] as $value) {
echo "Value: $value <br />";
}
}
The above gives an error; Warning: Invalid argument supplied for foreach() ...
If I write the function like this:
$array[] = $_SESSION['site_msg'];
foreach($array as $value) {
echo "VAL: " . $value;
}
It only gives me the last value, 20.
Anyone have an idea where I went wrong?
Thanks!
<?php
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
array_push($_SESSION['site_msg'],18); // '=' overwrites the data, so push data in session array not to assign
}
if(2 == 2) {
array_push($_SESSION['site_msg'],21);
}
if(3 == 3) {
array_push($_SESSION['site_msg'],20);
}
$array = $_SESSION['site_msg']; //remove [] from variable, its not needed
foreach($array as $value) {
echo "VAL: " . $value;
}
?>
You declare your variable $_SESSION['site_msg'] as an array, but you pass integer values to this variable! You need to add your values as new array elements.
This should work:
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
$_SESSION['site_msg'][] = 18;
}
if(2 == 2) {
$_SESSION['site_msg'][] = 21;
}
if(3 == 3) {
$_SESSION['site_msg'][] = 20;
}
As an alternative you can use the function array_push() to add your values to the array:
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
array_push($_SESSION['site_msg'], 18);
}
if(2 == 2) {
array_push($_SESSION['site_msg'], 21);
}
if(3 == 3) {
array_push($_SESSION['site_msg'], 20);
}

How to list items in alphabetical order with a heading and if no match is found display a message

My plan of action was:
Loop through an array of the alphabet
While inside of that loop, print the current letter
While inside of that loop cycle through a list of city objects stored in an array.
Check and see if the first letter of the $city->city_name property matches the current letter in the loop. If it matches, print it.
If there are no matches, print a message saying so.
This is all I can get it to display:
A
There are no results to display.
B
There are no results to display.
C
City
There are no results to display.
D
There are no results to display.
E
City
There are no results to display.
As you can see, the error displays even if there is a match. I cannot seem to figure out where the flaw in my logic is and I've searched through every question on the topic. Is there something obvious that I am missing?
Code:
<?php
function printValues($cities, $county)
{
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$letters = str_split($str);
$lettersMatched = FALSE;
foreach ($letters as $letter)
{
echo "<h5 class=\"letter\">".$letter."</h5><hr>";
foreach ($cities as $city)
{
if(substr($city->city_name, 0, 1) == $letter)
{
$lettersMatched = TRUE;
$result = $city->city_name;
echo "<p>".$result."</p>";
$lettersMatched = FALSE;
}
}
if (!$lettersMatched)
{
echo "<p>There are no results to display.</p>";
}
}
}
?>
You're resetting $lettersMatched to false inside the if statement. Try this:
<?php
function printValues($cities, $county)
{
$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$letters = str_split($str);
//$lettersMatched = FALSE;
foreach ($letters as $letter)
{
echo "<h5 class=\"letter\">".$letter."</h5><hr>";
$lettersMatched = FALSE;
foreach ($cities as $city)
{
if(substr($city->city_name, 0, 1) == $letter)
{
$lettersMatched = TRUE;
$result = $city->city_name;
echo "<p>".$result."</p>";
// $lettersMatched = FALSE;
}
}
if (!$lettersMatched)
{
echo "<p>There are no results to display.</p>";
}
}
}
?>
$matches = false;
foreach(range('A', 'Z') AS $letter)
{
echo $letter . '<hr>';
foreach( $cities AS $city )
{
if( strtoupper(substr($city->city_name, 0, 1)) === $letter)
{
$matches = true;
echo "<p>" . $city->city_name . "</p>";
}
}
if(!$matches)
echo "<p>No matches here</p>";
$matches = false;
}
What you did was to set the matches to false right after you set it to true in the inner loop. So when your code reaches the condition outside the loop it will always be false.
What I did was to set the matches to false after the condition, so it will be checked again for each new letter.

foreach trying to make 3 parameters

Is there a way I could make this happen? Its like foreach with 3 paramaters
Something like this
foreach ($value as $v,$value2 as $v2,$value3 as $v3)
<?php echo $v->name?>
<?php echo $v->actual?>
<?php echo $v2->estimated?>
<?php echo $v3->projected?>
I think you want
foreach ($value as $v)
{
foreach($value2 as $v2)
{
foreach($value3 as $v3)
{
echo $v->name;
echo $v->actual;
echo $v2->estimated;
echo $v3->projected;
}
}
}
Or:
foreach ($value as $v,$value2 as $v2,$value3 as $v3)
{
echo $v->name;
echo $v->actual;
}
foreach($value2 as $v2)
{
echo $v2->projected;
}
foreach($value3 as $v3)
{
echo $v3->estimated;
}
Which you may have known, but I don't think it's possible to actually put all three into one like you're asking.
EDIT: With a bit more information on what your $value arrays contain, it may be easier to provide you with a solution that can help you more easily accomplish what you're trying to do.
To retrieve next elements from each array in every iteration:
do{
$v = current($value);
$v2 = current($value2);
$v3 = current($value3);
// ...
} while(next($value) !== false && next($value2) !== false && next($value3) !== false);
Assuming they have equal length, are not empty and contain no falses.
You may also want to use for loop:
for($i = 0; $i < count($value); $i++){
$v = $value[$i];
$v2 = $value2[$i];
$v3 = $value3[$i];
// ...
}
Assuming their keys are numeric and they have equal length.

Getting a particular array and echo its value

I have this script from a free website file. Here is the subject script:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
How to get the value of ID and echo it?
When you clean up the code, it’s easy to see how to access the ID value:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
if ($a == 'ID') {
echo $a1;
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
Just adding the check for ID will work:
if ($a == 'ID') {
echo $a1;
}
EDIT And if you want to access it outside of the foreach loop, just do this. I have an if conditional to just check if the value exists.
if (array_key_exists('ID', $auth) && !empty(trim($auth['ID'])) {
echo $auth['ID'];
}
Or, since your foreach loop is creating $results you can access that value this way instead:
if (array_key_exists('ID', $results) && !empty(trim($results['ID'])) {
echo $results['ID'];
}

Categories