PHP find equal variables - php

Is there a way to easily check if the values of multiple variables are equal? For example, in the code below I have 10 values, and it's cumbersome to use the equal sign to check if they're all equal.
<?
foreach($this->layout as $l):
$long1=$l['long1_campaignid'];
$long2=$l['long2_campaignid'];
$long3=$l['long3_campaignid'];
$long4=$l['long4_campaignid'];
$long5=$l['long5_campaignid'];
$long6=$l['long6_campaignid'];
$long7=$l['long7_campaignid'];
$long8=$l['long8_campaignid'];
$long9=$l['long9_campaignid'];
$long10=$l['long10_campaignid'];
endforeach;
?>
for example
if $long1=3,$long2=7,$long3=3,$long4=7,$long5=3 etc,
i need to retrieve $long1=$long3=$long5 and $long2=$long4

I think this is what you're looking for:
<?
foreach($this->layout as $l):
$m = array_unique($l);
if (count($m) === 1) {
echo 'All of the values are the same<br>';
}
endforeach;
?>
I assuming that you are looking to see if all of the values in the array are the same. So to do this I call array_unique() to remove duplicates from the array. If all of the values of the array are the same this will leave us with an array of one element. So I check for this and if it is true then all of the values are the same.

The example showed at the question is about "grouping" not directly about "find equal variables".
I think this simple "grouping without change the order" algorithm is the answer... Other algorithms using sort() are also easy to implement with PHP.
<?
foreach($this->layout as $l) {
$m = array();
foreach($1 as $k=>$v) // keys 'longX' and values
if (array_key_exists($v,$m)) $m[$v][] = $k;
else $m[$v] = array($k);
foreach ($m as $val=>$keys)
if (count($keys)>1) echo "<br/> have SAME values: ".join(',',$keys)
}
?>
About "find equal variables"
Another (simple) code, see Example #2 at PHP man of array_unique.
<?
$m = array_unique($this->layout);
$n = count($m);
if ($n == 1)
echo 'All of the values are the exactly the same';
elseif ($n>0)
echo 'Different values';
else
echo 'No values';
?>
The "equal criteria" perhaps need some filtering at strings, to normalize spaces, lower/upper cases, etc. Only the use of this "flexible equal" justify a loop. Example:
<?
$m = array();
foreach($this->layout as $l)
$m[trim(strtolower($1))]=1;
$n = count(array_keys($m));
if ($n == 1)
echo 'All of the values are the exactly the same';
elseif ($n>0)
echo 'Different values';
else
echo 'No values';
?>

If #John Conde's answer is not what you are looking for and you want to check for one or more of the same values in the collection, you could sort the array and then loop through it, keeping the last value and comparing it to the current value.

Related

Where is the wrong in this foreach?

In the following structure:
$numbers = array("one", "two", "three", "four");
foreach ($numbers as $value) {
if( $value == 'two' ) {
echo '$value <br>';
}
else {
echo 'This numbers doesnt exist in the array';
}
}
I intend that if one of the if values is equal to two (in this case one of the values is equal to 2), I print the entire array, that is, one, two, three, and four, and for example, if I put that the if is equal to 5, since that value does not exist in the array, it is entered through the else. From the code I have provided, what have I done wrong?
The way your code works currently, you are iterating through each value in the array. If the value you are up to is the sentinel value (in this case the string "two") then you are printing it, otherwise you are printing another message.
If you wish to print the entire array if and only if it contains the sentinel value, you can use in_array() to check for the existence of the sentinel value first:
$sentinel = 'two';
if ( in_array($sentinel, $numbers ) ) {
foreach ( $numbers as $number ) {
echo "$number<br>";
}
} else {
echo "The number $sentinel does not exist in the array.";
}

echo a number in php

I am trying to learn php, and I am playing around with while loops. I was wondering how to print out a specific number in an array in php. Fx:
$a = [1,3,5,7,9,11,13];
$s = 3;
while($a == 3) {
echo $s.' is in the row';
$a++;
}
In this example I would like to run through the $a and see if 3 exist there. If it does it has to echo '3 is in the row' I tried to make a while loop, but it is not correct. Can anyone see what I am doing wrong? Just to say it, I think it is very wrong, but I don't know how to solve it, if I have to use the while loop?
Best Regards
Mads
Your while condition reads: "While the value of $a equals 3", but $a is an array, so its value can't ever be 3. The loop will never be executed. In PHP, we would write:
if (in_array($s, $a))
echo $s, ' was found in the array';
Or, if you insist on writing loops:
foreach ($a as $key => $value)
{
if ($value == $s)
{
echo $s, ' was found at offset ', $key;
break;//end terminate loop
}
}
Of course, you could also write:
for ($i=0, $j=count($a);$i<$j;++$j)
{
if ($a[$i] == $s)
{//you could move this condition to the loop itself, even
echo $s, ' found in array at offset ', $i;
break;
}
}
You can, if you want use a while loop, too, but that wouldn't be the best choice for your particular case. Just read through the manual on php.net. There are many, many array_* functions available, and there are many ways to iterate over your data.
Another worry is your using the array name as a sort-of C-style pointer: $a++; in C, an pointer can be incremented to set it to point to the next value in an array (if the new memory address is valid, and the pointer is valid, and all of the other things you have to worry about in C). PHP does not work this way. An array isn't really an array: it's a hash map. incrementing an array, therefore, is pointless and most likely to be a bug. The for loop is the closest you can get to traversing an array using the ++ operator.
You're looking for in_array. This checks if a value exists in an array, in the form of:
in_array ( mixed $needle , array $haystack )
So, in your case, you'd want to do:
$a = [1,3,5,7,9,11,13];
$s = 3;
if (in_array($s, $a)) {
echo $s.' is in the row';
}
foreach($a as $b) {
if($b == 3)
echo $b.' is in the row';
}
Modify slightly your code changing while condition:
$a = array(1,3,5,7,9,11,13);
$s = 3;
$counter = 0;
while($counter < count($a)) {
if ( $a[$counter] == $s )
echo $s.' is in the row';
$counter++;
}
Added counter to iterate through while loop until end of array.
count() method returns number of items in array.
This solution prints all occurences of your number.
To have better code, change names of variables:
$numbers = array(1,3,5,7,9,11,13);
$target = 3;
$counter = 0;
while($counter < count($numbers)) {
if ( $numbers[$counter] == $target )
echo $target.' is in the row';
$counter++;
}
There are two ways to do it,
First, you can loop through all items in the array using a foreach() loop.
That way, you can go through them all and if you have multiple conditions, it makes your code a bit more readable.
And example of that loop is like this:
foreach($array as $array_item) {
if($array_item === 3) {
echo "3 is in the array";
}
}
The alternative is to use a built in function to find if something is in the array. THis is probably much faster, though I haven't benchmarked the difference.
if(in_array(3, $array)) {
echo "3 is in the array";
}
you can use
array_search ,in_array , and forearch or for loops to itertate through the array.
For learning purposes
$a = [1,3,5,7,9,11,13];
$s = 3;
for($i=0;$i<count($a);$i++)
{
if($a[$i]==$s){
echo $s.' is in the row';
}
}
of course in real life
if (in_array(3, $a)) {
// Do something
}
would be better;
<?php
$a = [1,3,5,7,9,11,13];
$s = 3;
for($a=0;$a < 20; $a++)
{
while($a == 3) {
echo $s.' is in the row';
//$a++;
}
}
?>

php MySQL fetch printing double?

When I make a sql query and echo it out it repeats the first row twice
$sql = 'SELECT one,two,three FROM justAnExampleForSO where one = one';
$info = mysql_query(sql);
if(mysql_num_rows($info )>0){
while ($row = mysql_fetch_array($info )) {
foreach($row as $key => $var)
{
if($key == 'one')
echo $var.",";
else if($key == 'two')
echo $var.",";
else if($key == 'three')
echo $var.";";
}
}
}
so for example say I am attempting to get cols one, two, three
When the output is echoed it would echo
one, one, two,three;
I am not sure if this is a duplicate of this question or not because I couldn't full understand his problem. Fetch array function doubling values in each position of array?
Because mysql_fetch_array returns both numerically indexed values and string indexes, and due to the fun of type casting rules "one" equals 0. Use === instead of == to prevent that, or use mysql_fetch_assoc to forgo the numerical indexes you're not using anyway.
You should also be doing it much more simply than a foreach..if..else:
echo $row['one'], ', ', $row['two'], ', ', $row['three'], ';';

Elegant Method of Inserting Code Between Loops

In web development, I often find I need to format and print various arrays of data, and separate these blocks of data in some manner. In other words, I need to be able to insert code between each loop, without said code being inserted before the first entry or after the last one. The most elegant way I've found to accomplish this is as follows:
function echoWithBreaks($array){
for($i=0; $i<count($array); $i++){
//Echo an item
if($i<count($array)-1){
//Echo "between code"
}
}
}
Unfortunately, there's no way that I can see to implement this solution with foreach instead of for. Does anyone know of a more elegant solution that will work with foreach?
I think you're looking for the implode function.
Then just echo the imploded string.
The only more elegant i can think of making that exact algorithm is this:
function implodeEcho($array, $joinValue)
{
foreach($array as $i => $val)
{
if ($i != 0) echo $joinValue;
echo $val;
}
}
This of course assumes $array only is indexed by integers and not by keys.
Unfortunately, I don't think there is any way to do that with foreach. This is a problem in many languages.
I typically solve this one of two ways:
The way you mention above, except with $i > 0 rather than $i < count($array) - 1.
Using join or implode.
A trick I use sometimes:
function echoWithBreaks($array){
$prefix = '';
foreach($array as $item){
echo $prefix;
//Echo item
$prefix = '<between code>';
}
}
If more elaborate code then an implode could handle I'd use a simple boolean:
$looped = false;
foreach($arr as $var){
if($looped){
//do between
}
$looped = true;
//do something with $var
}

PHP display problem?

For some reason when an array has for example, four values it will display all four values four times I just want the values to be displayed one time.
How can I fix this problem? Note the first echo works perfectly.
Here is the code.
if (count($array) == 1){
echo $array[$x] . " one value has been entered";
} else {
echo implode(", ", $array) ." you entered more then one value;
}
Because $x obviously isn't the index of the first element of the array. Use the correct index. Or if you don't know what it is, just use reset():
if (count($array) == 1) {
echo reset($array) . ' one value has been entered';
} else {
echo implode(', ', $array) . ' you entered more than one value';
}
It might be helpful to dump the array to see what it actually contains:
print_r($array);
$x is not set in your code or just meaningless. If you have just one array item you can print it with the simple echo $array[0];

Categories