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.";
}
Related
I have an array that looks like this...
Array
(
[0] => red
[1] => red
[2] => red
)
I am trying to check if red is the only thing in the array, I would want it to fail if the array looked like this...
Array
(
[0] => red
[1] => yellow
[2] => red
)
Using array_unique() you can just count the number of occurances returned. If its > 1 you have not got all red
<?php
$array = ['red','red','red'];
if ( count(array_unique($array)) == 1 && array_unique($array)[0] == 'red' ) {
echo 'all red';
} else {
echo 'error';
}
Use combination of count() and array_filter() to find count of unwanted item in array.
$invalidItems = count(array_filter($arr, function($item){
return $item != 'red';
}));
if ($invalidItems)
echo 'invalid';
else
echo 'valid';
Check result in demo
You could just use array_unique() to get it to remove duplicates and then count the size of the remaining list, you can also then check that the 1 value is whatever value your expecting...
$unique = array_unique($a);
if ( count($unique) == 1 && $unique[0] == 'value' ) {
}
You can do it like this:
$array = [
'foo',
'foo',
'foo'
];
$values = array_count_values($array);
$count = count($array);
if (!empty($values['foo']) && $count === $values['foo']) {
echo 'all array values match foo';
} else {
echo 'foo not found in array';
}
here we count values in the array vs the overall count of the array
Edit: The only problem is, you have to know the value you're comparing against to get the result
Edit 2: Addressing issue raised by MickMackusa:
and the other problem is, if the value that you are looking for doesn't exist at all in the input array, then it won't exist as a key in the $values array and thus your code will generate a Notice. ...not good.
You don't need more than one function call to check for non-red values exist. The following checks if there are any non-red elements.
Codes (Demo)
$array = ['red','red','red'];
var_export(!array_diff($array, ['red'])); // true
echo "\n";
var_export(!array_filter($array, function($v){return $v !== 'red';})); // true
$array = ['red','yellow','red'];
var_export(!array_diff($array, ['red'])); // false
echo "\n";
var_export(!array_filter($array, function($v){return $v !== 'red';})); // false
I think array_filter() is a more "direct" technique, but array_diff() doesn't need a custom function so it is arguably easier to read.
If your coding logic must require the existence of red as well as disqualify arrays that contain a non-red element, then just add a condition that checks if the array has any elements. (more precise demo)
And for best performance, use a loop with a break -- this way you don't have to iterate the entire array unless absolutely necessary. Early breaks are a good thing. Demo
$array = ['red','yellow','red'];
$result = true;
foreach ($array as $value) {
if ($value != 'red') {
$result = false;
break;
}
}
Check if red is there, then remove duplicate values and check that there is only one:
if(in_array('red', $array) && (count(array_unique($array)) == 1)) {
// yes
}
Old school foreach (all) red or dead:
<?php
$things = ['red', 'white', 'blue'];
foreach($things as $colour)
if ($colour !== 'red')
throw new Exception('dead');
I want to echo one element of the array like sum1. But I only get one letter like s. Please solve this problem.
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value[0];
echo $value[1];
}
If you want to just echo 1 item from that array, you should to it like this:
echo $nums[0];
If you want to loop through all of them, and show each, do it like so:
$nums = array("sum1", 100, 200);
foreach ($nums as $value) {
echo $value."<br>";
}
What you did wrong
You had already looped through the array, so you had a string. You can select the first letter from a string like in this example:
$string = "A string";
echo $string[0];
Will return A, as it's the first index of that string. That is essentially what you did in your loop.
You made your String an array, and it showed the index's you selected to be shown. You can read this where the questions asks how to do this. I hope this gives some more clearity.
If you want every element of array,
then,
For your array,
$nums = array("sum1", 100, 200);
$nums[0] will be sum1
$nums[1] will be 100
$nums[2] will be 200,
Now your loop,
foreach ($nums as $value) {
// here echo $value values are like 'sum1', 100, 200 will be printed.
// by default string will be considered as array,
// if you print $value[0], $value[1], $value[2], $value[3] for sum1, it will return, s, u, m, 1 respectively.
// and integers will be considered as pure value, which you will get in $value only, not in $value[0], ....
}
I hope I explained your concern.
Thanks.
It's a simple question, but puzzling me:
$myarray = array(
array(10,20),
array(299, 315),
array(156, 199)
);
How do I check if given $x , lies in between, in any of those particular individual array values? I want to search each individual entry array.
For Example, I want to search, if $x is somewhere between: 10 to 20 and then between 299 to 315 and then between 156 to 199.
Try this:
function is_in_array_range($array, $search) {
foreach ($array as $value) {
$min = min($value);
$max = max($value);
if ($search >= $min && $search <= $max) {
return true;
}
}
return false;
}
$myarray = array(
array(10,20),
array(299, 315),
array(156, 199)
);
is_in_array_range($myarray, 9); // Returns false
is_in_array_range($myarray, 11); // Returns true
The function is_in_array_range() will take two arguments. The array, and the value you want to check is in the range.
When it enters, it will loop over all elements in the array. Every time it gets the highest and lowest value of the nested array (min() and max() function), and checks if the value you are looking for is between them. If this is the case, return true (this also stops the function). If true is never reached, the value is not found, so at the end of the function, return false.
this will do it code
foreach($myarray as $value)
{
if(in_array("10", $value, true))
{
echo "Got 10";
}
}
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++;
}
}
?>
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.