I'd like my function to have a comparison operator as an argument (or preferably, as part of an argument such as >0 ):
Instead of
function comps($a,$b){
if ($a > $b)
echo "This works.";
}
comps(1,0);
I'd like to be able to do something like
function comps($a,$b){
if ($a $b)
echo "This works.";
}
comps(1,'>0');
I've been banging my head agains the wall on this for a while. I've tried different iterations of:
"/>0"
'>' . 0
(string)> 0
as well as trying the comparison operator as a third argument.
Actual use is:
function mysort($key,$match){
$temp_array = array();
global $students;
foreach ($students as $row) {
if($row[$key] > $match )
$temp_array[]= $row;
}
foreach ($temp_array as $row) {
echo $row['email'] . ', ';
}
}
mysort('suzuki', '0');
Thanks
You can make a return type function and use as you want.
I'll Make a function to you as Below:
<?php
function getCond($a, $b, $both) {
$data = false;
if($both) {
if($a == b) {
$data = true;
}
}else {
if($a > $b) {
$data = true;
}
}
return $data;
}
/* Use Your Function */
if (getCond(10, 5, true)) { // condition for 10 == 5 and according to passed values you get false result in condition
echo "you result";
} else if (getCond(10, 5, false)) { // condition for 10 > 5 and according to passed values you get false result in condition
echo "your result";
} else if (getCond(6, 5, false)){ // condition for 6 > 5 and according to passed values you get true result in condition
echo "your result";
}
?>
You also can modify this function as you want :)
The simplest solution for my use seems to be:
function comps($a,$b,$c){
if ($a > $b and $a < $c)
echo "True";
}
comps(1,0,2);
?>
Related
I'm trying to find the number of strings that satisfy some conditions in a foreach loop. This is what I've tried so far:
<?php
$list = $item->getProperty();
$n = 0;
foreach($list as $single) {
$designation = $single->getPropertyName(); // var_dump($designation); outputs 150 strings
if (strpos($designation, 'foo') === 0) { // var_dump($designation); outputs 5 strings containing 'foo' in their designation names
$n++;
echo count($n);
}
}
?>
echo count($n); returns 11111 instead of returning 5 which is the value I want to obtain.
Could someone help me out a bit?
<?php
$list = $item->getProperty();
$n = 0;
foreach($list as $single) {
$designation = $single->getPropertyName(); // var_dump($designation); outputs 150 strings
if (strpos($designation, 'foo') === 0) { // var_dump($designation); outputs 5 strings containing 'foo' in their designation names
$n++;
}
}
echo $n;
If you would like to achieve the same in a more functional and elegant way, you could use array_reduce
array_reduce($item->getProperty(), function($sum, $single) {
if (strpos($single->getPropertyName(), 'foo') === 0) {
$sum++;
}
return $sum;
});
A less readable, but more elegant one-line solution would look like:
array_reduce($item->getProperty(), function($sum, $single) { return (strpos($single->getPropertyName(), 'foo') === 0) ? ++$sum : $sum; }
And now that we have short arrow functions in PHP, you can use this if you are running on PHP 7.4:
array_reduce($item->getProperty(),
fn($sum, $single) => (strpos($single->getPropertyName(), 'foo') === 0) ? ++$sum : $sum);
How do I find if an array has one or more elements?
I need to execute a block of code where the size of the array is greater than zero.
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
You can use the count() or sizeof() PHP functions:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Or you can use:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
count — Count all elements in an array, or something in an object
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Counts all elements in an array, or something in an object.
Example:
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
In your case, it is like:
if (count($array) > 0)
{
// Execute some block of code here
}
If you want to only check if the array is not empty, you should use empty() - it is much faster than count(), and it is also more readable:
if (!empty($result)) {
// ...
} else {
// ...
}
You could avoid length retrieve and check using a simple foreach:
foreach($result as $key=>$value) {
echo $value;
}
#Sajid Mehmood in PHP we have count() to count the length of an array,
when count() returns 0 that means that array is empty
Let’s take an example for your understanding:
<?php
$arr1 = array(1); // With one value which will give 1 count
$arr2 = array(); // With no value which will give 0 count
// Now I want that the array which has greater than 0 count should print other wise not so
if (count($arr1)) {
print_r($arr1);
}
else {
echo "Sorry, array1 has 0 count";
}
if (count($arr2)) {
print_r($arr2);
}
else {
echo "Sorry, array2 has 0 count";
}
Pro Tip:
If you are sure that:
the variable exists (isset) AND
the variable type is an array (is_array) ...might be true of all is_iterables, but I haven't researched that extension of the question scope.
Then you don't need to call any functions. An array with one or more elements has a boolean value of true. An array with no elements has a boolean value of false.
Code: (Demo)
var_export((bool)[]);
echo "\n";
var_export((bool)['not empty']);
echo "\n";
var_export((bool)[0]);
echo "\n";
var_export((bool)[null]);
echo "\n";
var_export((bool)[false]);
echo "\n";
$noElements = [];
if ($noElements) {
echo 'not empty';
} else {
echo 'empty';
}
Output:
false
true
true
true
true
empty
For those who start with the array in PHP presented it this way:
more information here
//Array
$result = array(1,2,3,4);
//Count all the elements of an array or something of an object
if (count($result) > 0) {
print_r($result);
}
// Or
// Determines if a variable is empty
if (!empty($result)) {
print_r($result);
}
// Or
// sizeof - Alias of count ()
if (sizeof($result)) {
print_r($result);
}
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>
I'm trying to find a native php function which returns true if there is exactly one occurrence of any given element in an array.
For example:
$searchedForValue = 3;
$array1 = [1,2,3,4,5,6];
$array2 = [1,2,3,3,4,5];
$array3 = [1,2,4,5,6];
oneOccurrence($array1,$searchedForValue);
oneOccurrence($array2,$searchedForValue);
oneOccurrence($array3,$searchedForValue);
This should return:
true
false
false
Cheers
You should use array_count_values() here.
$array_values = array_count_values($array2);
This will return an array. Key denotes each element of $array2 and value denotes frequency of each element.:
Array (
[1] => 1
[2] => 1
[3] => 2 // Denotes 3 appears 2 times
[4] => 1
[5] => 1
)
if (#$array_values[$searchedForValue] == 1) {
echo "True";
} else {
echo "False";
}
This does what you want. Bare in mind, echoing oneOccurence won't output 'true' or 'false', it returns a boolean.
function oneOccurrence ($arr, $val) {
$occurrences = [];
foreach ($arr as $v) {
if ($v == $val) {
$occurrences[] = $v;
}
}
return count($occurrences) == 1;
}
P.S echo doesn't need brackets as it's a PHP construct.
A small utility function - count array values using array_count_values and then if the search key exists and if its count is exactly 1, return true otherwise false:
function oneOccurrence($array, $searchValue) {
$array = array_count_values($array);
return (array_key_exists($searchValue, $array) && $array[$searchValue]==1)?true:false;
}
Check EVAL
Since you are searching for one occurrence: http://codepad.org/cZImb4FI
Use array_count_values()
<?php
$searchedForValue = 3;
$array1 = array(1,2,3,4,5,6);
$array2 = array(1,2,3,3,4,5);
$array3 = array(1,2,4,5,6);
$arr = array($array1,$array2 ,$array3);
function array_count_values_of($value, $array) {
$counts = array_count_values($array);
return $counts[$value];
}
foreach($arr as $ar){
if( array_count_values_of($searchedForValue,$ar)==1){echo "true";}else{echo "false";}
}
?>
output
true false false
//In Php in_array() function is provided..
$searchedForValue = 3;
$array1 = array(1,2,3,4,5,6);
$array2 = array(1,2,3,3,4,5);
$array3 = array(1,2,4,5,6);
if(in_array($searchedForValue,$array1))
{
echo "true";
}
else
{
echo "false";
}
if(in_array($searchedForValue,$array2))
{
echo "true";
}
else
{
echo "false";
}
if(in_array($searchedForValue,$array3))
{
echo "true";
}
else
{
echo "false";
}
I have 2 explode arrays from the database. and this is what i did.
$searches = explode(',', $searchengine);
$icons = explode(',', $icon);
$b = count($searches);
$c = count($icons);
I also made an array to compare each explode array to.
$searchesa = array("google","yahoo","bing");
$d = count($searchesa);
$iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo");
$y = count($iconsa);
Then i used for loops to travel to different array indexes. But the result is wrong, and sometimes I have an error which says UNDEFINED OFFSET.
for ($a=0; $a <$d ; $a++) {
if ($searches[$a] == $searchesa[$a])
{echo '<br>'.$searchesa[$a].': check ';
}else
echo '<br>'.$searchesa[$a].': chok ';
}
for ($x=0; $x <$y ; $x++) {
if ($icons[$x] == $iconsa[$x])
echo '<br>'.$iconsa[$x].': check ';
else
echo '<br>'.$iconsa[$x].': chok ';
}
If the index from the database and the array I made are the same, it will state check, else it will state chok.
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
taken via :
PHP - Check if two arrays are equal
I posted this in my comment, but I suppose the outline will work better in an answer.
I hope this could be of any help:
<?php
$array_a = ['test','test2']; // assume this is your first array
$array_b = ['test']; // assume this is the array you wan to compare against
$found = false;
foreach ($array_a as $key_a => $val_a) {
$found = false;
foreach ($array_b as $key_b => $val_b) {
if ($val_a == $val_b) {
echo '<br>'. $val_b .': check ';
$found = true;
}
}
if (!$found)
echo '<br>'. $val_a .': chok ';
}
?>
EDIT: Please excuse me for not testing it.
This thing will loop through the first array, and compare it with every value in the other array.
Tip: You can easily put this in a function and call it like compare($arr1, $arr2)
You can try in_array method:
$searchesa = array("google","yahoo","bing");
$iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo",'google');
foreach($searchesa as $val){
if(in_array($val, $iconsa)){
echo "check";
} else {
echo "choke";
}
}
Note: I've added "google" in $iconsa array.
If I understand you correctly this is what you are looking for:
// Lets prepare the arrays
$searchEngines = explode(',', $searchengine);
$icons = explode(',', $icon);
// Now let's define the arrays to match with
$searchEnginesCompare = array(
'google',
'yahoo',
'bing'
);
$iconsCompare = array(
'facebook',
'twitter',
'googleplus',
'linkedin',
'pinterest',
'delicious',
'stumbleupon',
'diigo'
);
// Check the search engines
foreach ($searchEngines as $k => $searchEngine) {
if (in_array($searchEngine, $searchEnginesCompare)) {
echo $searchEngine." : check<br />";
} else {
echo $searchEngine." : failed<br />";
}
}
// Now let's check the icons array
foreach ($icons as $k => $icon) {
if (in_array($icon, $iconsCompare)) {
echo $icon." : check<br />";
} else {
echo $icon." : failed<br />";
}
}
I'm having a trouble. I was trying to make it work for a long time, so I decided to ask for help here.
I have an with some arrays inside it:
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
I am making a function that search for a s
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
break;
}
else {
searchArray($key,$chave,$id);
}
}
}
return $key;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
It was supposed to print ['string6','string7','string99']]
But it it printing the last "key" of the array: ['string8','string9']
The break is not working. After the break, it continue checking the next arrays.
with these modification it returns the expected values:
<?php
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
return $key;
} else {
$res = searchArray($key,$chave,$id);
if($res !== false) {
return $res;
}
}
}
}
return false;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
the failure was to break on success. That makes no sense.
You need to return the value on success. If no success return false. Imagine it may happen that the searched values will not been found so it should return false.