I have this function:
protected function compare_something($found_item, $saved_items)
{
foreach($saved_items as item) {
$compare_x = false;
$compare_y = false;
$compare_z = false;
$compare_x = strpos($found_item,$item->x) !== false ? true: false;
$compare_y = strpos($found_item,$item->y) !== false ? true: false;
$compare_z = strpos($found_item,$item->z) !== false ? true: false;
if($compare_x && $compare_y && $compare_z){
return $item;
}
}
return false;
}
I expect $item to be the object where $compare_x, $compare_y and $compare_z are true, however this function simply returns the entire eloquent object ($saved_items) instead of the compared one.
I am not sure why is this happening. I can always return:
$item->id
And then do Item::where("id",$item->id)->first();
But shouldn't just return $item just deliver me the chosen item?
Eloquent queries always return a collection, so you can easily use the filter function for this. After that call the first function to get the first element. If there are no elements in the collection, null will be returned.
For example:
return $saved_items->filter(function ($item) use ($found_item) {
return strpos($found_item, $item->x) !== false &&
strpos($found_item, $item->y) !== false &&
strpos($found_item, $item->z) !== false;
})->first();
Related
I want to count the recurrence of a true or false and output which has the most. Is there a predefined function to do this in PHP? So far I have done it like this (isHappy() method):
class Girl {
private $issues = [];
public function addIssue($details) {
this->issues[] = [$details, false];
return;
}
public function isHappy() {
$true = [];
$false = [];
foreach($this->issues as $issue) {
if($issue[1]) { $true[] = true; } else { $false[] = false; }
}
// what if its == to one another? do we return happy or sad?
return count($true) < count($false) ? false : true;
}
public function resolveIssue() {
for($i = 0; $i <= count($this->issues); $i++) {
if(!$this->issues[$i][1]) {
$this->issues[$i][1] = true;
break;
}
}
return;
}
}
So when I run it, I can get the average of if she is happy or not:
$her = new Girl();
$her->addIssue('Deleted our messages');
$her->addIssue('Over reacted');
$her->addIssue('Told her family to pretty much **** off');
echo $her->isHappy() ? 'it is all ok:)' : 'she hates u, hang urself.';
P.S: It should probably return false every time cos you can't win.
You want array_count_values:
function isHappy(array $issues) {
$happiness = array_count_values(array_map('intval', $issues));
return $happiness[1] > $happiness[0];
}
print_r(
isHappy([ true, false, true, true, false ])
);
See it live on 3v4l.org.
Note that array_count_values only works on string and int, so I'm mapping the given boolean to int for processing.
array_sum() type juggles for you, so simply compare the sum of all true with all issues minus the true (which yields all false):
public function isHappy() {
return ($true = array_sum($this->issues)) > (count($this->issues) - $true);
}
Get the keys where the value is true and count it, do the same for false and compare:
return count(array_keys($this->issues, true)) > count(array_keys($this->issues, false));
Or a number of other possible combinations.
I want a simple but correct way to check if true or false was returned from a codeigniter model.
SO
If true was returned by my model, can I just do this in the controller?
if($variable = $this->ci_model->model_method($user_id)){
// true, was returned do something
}
Or do i have to specifically test if true was returned, and how can i do that?
Do this :
$variable = $this->ci_model->model_method($user_id);
if(!empty($variable))
{
return true
}
else
{
return false;
}
OR you can this way :
if($this->ci_model->model_method($user_id))
{
return true
}
else
{
return false;
}
I want to make a member search with some filter options.
I tried filter(), but I got this error:
Fatal error: Call to a member function filter() on array
It works when I use only one filter, because it only returns the id's.
Is their a way I can use filter() multiple times, this is my code:
$members = User::all();
if ($has_avatar) {
$members = $members->filter(function ($member) {
//Avatar is not empty, other wise false
return ($member->avatar != "") ? true : false;
});
}
if ($is_online) {
$members = $members->filter(function ($member) {
//User is now online, other wise false
return ($member->is_online == 1) ? true : false;
});
}
Or is there a other way to achieve this?
As documentation says at https://laravel.com/docs/5.2/collections#method-filter, this method returns only a plain array.
You could try:
$members->filter(function ($member) {
return ($member->avatar != "") && ($member->is_online == 1);
});
I think the issue is that in Laravel 5.2 the all() method returns an array now.
Try using:
$members = User::get();
if ($has_avatar) {
$members = $members->filter(function ($member) {
//Avatar is not empty, other wise false
return ($member->avatar != "") ? true : false;
});
}
if ($is_online) {
$members = $members->filter(function ($member) {
//User is now online, other wise false
return ($member->is_online == 1) ? true : false;
});
}
How can I use foreach to return true or false.
For example, this isn't working.
function checkArray($myArray) {
foreach( $myArray as $key=>$value ) {
if(!$value == $condition) {
return false;
}
else {
return true;
}
}
if ($checkArray == true) {
// do something
}
What is the correct syntax for using foreach as true/false function? If you can't do it, could you use it to change an existing variable to true/false instead?
You would return true if the element was found/condition is true. And after the loop return false - if it had been found, this statement wouldn't have been reached.
function checkArray($myArray) {
foreach($myArray as $key => $value) {
if ($value == $condition) {
return true;
}
}
return false;
}
if (checkArray($array) === true) {
// ...
}
Of course true and false are interchangeable, depending on what output you expect.
If you're just trying to find a value you can use
if (in_array($lookup, $arrayToSearch)) { }
It'll be more efficient than enumerating the whole array.
Have
$my_arr_1 = array ("denied","denied","denied");
$my_arr_2 = array ("denied","denied","allowed");
Need a func that would check if all elements in the array equal to something:
in_array_all("denied",$my_arr_1); // => true
in_array_all("denied",$my_arr_2); // => false
Is there a php native function like in_array_all?
If not, what would be the most elegant way to write such a func?
function in_array_all($value, $array)
{
return (reset($array) == $value && count(array_unique($array)) == 1);
}
function in_array_all($needle,$haystack){
if(empty($needle) || empty($haystack)){
return false;
}
foreach($haystack as $k=>$v){
if($v != $needle){
return false;
}
}
return true;
}
And if you wanted to get really crazy:
function in_array_all($needle,$haystack){
if(empty($needle)){
throw new InvalidArgumentException("$needle must be a non-empty string. ".gettype($needle)." given.");
}
if(empty($haystack) || !is_array($haystack)){
throw new InvalidArgumentException("$haystack must be a non-empty array. ".gettype($haystack)." given.");
}
foreach($haystack as $k=>$v){
if($v != $needle){
return false;
}
}
return true;
}
I don't know the context of your code. But what about reversing the logic? Then you are able to use PHP's native function in_array.
$my_arr_1 = array ("denied","denied","denied");
$my_arr_2 = array ("denied","denied","allowed");
!in_array("allowed", $my_arr_1); // => true
!in_array("allowed", $my_arr_2); // => false
This entirely depends on your data set of course. But given the sample data, this would work. (Also, notice the negation ! in front of each method call to produce the desired boolean result).
Another solution using array_count_values():
function in_array_all(array $haystack, $needle) {
$count_map = array_count_values($haystack);
// in your case: [ 'denied' => 2, 'allowed' => 1 ]
return isset($count_map[$needle]) && $count_map[$needle] == count($haystack);
}
Richard's solution is best but does not have one closing paren ;-) - here is fixed and abridged:
function in_array_all($needle,$haystack)
{
if( empty($needle) || empty($haystack) ) return false;
foreach($haystack as $v)
{
if($v != $needle) return false;
}
return true;
}