check is Array empty or not (php) - php

I am using Cakephp and try to customize the paginator result with some checkboxes .I was pass parameters in URL like this
"http://localhost/myproject2/browses/index/page:2/b.sonic:1/b.hayate:7/b.nouvo:2/b.others:-1/b.all:-2"
and cakephp translate URL to be the array like this
Array
(
[page] => 2
[b.sonic] => 1
[b.hayate] => 7
[b.nouvo] => 2
[b.others] => -1
[b.all] => -2
)
other time when I pass params without checking any checkbox.
"http://localhost/myproject2/browses/index/page:2"
and cakephp translate URL to be the array like this
Array
(
[page] => 2
)
how to simple check if [b.????] is available or not? I can't use !empty() function because array[page] is getting on the way.

If you want to check if a specific item is present, you can use either :
isset()
or array_key_exists()
But if you want to check if there is at least one item which has a key that starts with b. you will not have much choice : you'll have to loop over the array, testing each key.
A possible solution could look like this :
$array = array(
'page' => 'plop',
'b.test' => 150,
'b.glop' => 'huhu',
);
$found_item_b = false;
foreach (array_keys($array) as $key) {
if (strpos($key, 'b.') === 0) {
$found_item_b = true;
break;
}
}
if ($found_item_b) {
echo "there is at least one b.";
}
Another (possibly more fun, but not necessarily more efficient ^^ ) way would be to get the array of items which have a key that starts with b. and use count() on that array :
$array_b = array_filter(array_keys($array), function ($key) {
if (strpos($key, 'b.') === 0) {
return true;
}
return false;
});
echo count($array_b);

If page is always going to be there, you could simply do a count.
if (count($params) == 1) {
echo "There's stuff other than page!";
}
You could be more specific and check page is there and the count is one.

I think this is what you are looking for, the isset function so you would use it like...
if(isset(Array[b.sonic]))
{
//Code here
}

Related

How to validate if two dates in array are not same with Carbon

I am using the Laravel framework, I have an array of dates where I want to check if there are two same dates exist. The array is this
array:5 [▼
0 => "2020-04-11"
1 => "2020-04-11"
2 => "2020-04-12"
3 => "2020-04-13"
4 => "2020-04-21"
]
I have written the following function to check, it works but I curious if there is any better way to achieve this because I have to extend it soon so there will be more nested loops.
private function validateFlyingDatesAreOverlapping($flyingDates)
{
foreach ($flyingDates as $key => $datePick) {
$datePickInstance = Carbon::parse($datePick)->startOfDay();
foreach ($flyingDates as $index => $dateCompare) {
$dateCompare = Carbon::parse($dateCompare)->startOfDay();
if ($key != $index) {
$result = $datePickInstance->eq($dateCompare);
if ($result) {
return true;
}
}
}
}
return false;
}
You can use collection unique and count method:
$is_same_exists = !(collect($data)->count() == collect($data)->unique()->count());
If you just need to know if duplicates is exists without getting the values (your function returns boolean, so looks like this is what you need), then you can just compare the count of items in the initial array with count of unique items in array, like this:
if (count(array_unique($array)) != count($array)) {
//duplicates is exists
}

PHP class to find value in array from session

I am trying to make a simple class that I can use to check if a value exists within an array. There is a session that contains multiple tool values. I am trying to pass the toolID to this function as well as a key and see if that value exists.
Session Data:
Array
(
[keyring] => Array
(
[tool] => Array
(
[toolID] => 1859
[keys] => Array
(
[0] => 49
[1] => 96
)
)
)
)
class Keyring
{
public function checkKey($key, $toolID){
$keyring = $_SESSION['keyring'];
if(isset($keyring)){
foreach($keyring['tool'] as $k => $v) {
if($k == 'toolID' && $v == $toolID){
if (in_array($key, $k->keys)){
return true;
}
}
}
}
return false;
}
}
$keyring = new Keyring();
print_r($keyring->checkKey(49, 1859));
In this example, I am trying to see if key 49 exists in the session for tool 1859.
I am getting the following error : Warning: in_array() expects parameter 2 to be array, null given in.
Is there a better approach for this? All I am looking for is a true/false as to whether that key exists in the keys array for the specified tool.
For my code to work for you may need to change your array a bit or change the code a bit, but rather then looping through a bunch of keys trying to find the right one we are just looking for the keys in the array if they are not set, then return false, or if we find keyring - tools - $tool_id - key_{$key_id} we are just going to return that value, if key_49 = false the function returns false. This should be a tad bit quicker to run on the server for you.
function has_keyring($tool_id, $key_id)
{
//Just to keep the code tidy let's store the tools key in $tool variable
$tool = $_SESSION['keyring']['tools'];
if(isset($tool[$tool_id]) && isset($tool[$tool_id]["key_{$key_id}"]))
return $tool[$tool_id]["key_{$key_id}"];
return false;
}

array_filter to check for conditions?

Can i use array_filter to check for specific conditions in a multidimensional array to replace an if() statement?
Want it to replace something like this:
if($item[0] == $key && $item[1] == "Test"){
//do something here....
}else{
//some other code here...
}
Current Array:
Array
(
[Zone] => Array
(
[Type] => s45
[packageA1] => Array
(
[level] => REMOVE FROM DB
[stage] => REMOVE FROM DB
[description] => description goes here
[image] => NULL
)
)
)
I want to search FIRST to see if [Type] exists. If it DOESN'T exist then i think ill use array_splice to insert it into the existing array. If it DOES exist then ill check if [packageA1] exists, if [packageA1] DOESN'T exist then i'll use array_splice once again. If [packageA1] DOES exist then ill skip over any type if inserting..
Does that make sense?
array_filter is designed for filtering arrays, not replacing boolean logic based on the contents of arrays.
array_filter takes 2 parameters - input and callback.
The callback function should take a single parameter (an item from the array) and return either true or false. The function returns an array with all of the items which returned false removed.
(If no callback function is specified, all items equal to false will be removed from the resulting array.)
Edit:
Based on your updated text, the below code should do what you want:
if (!$item['Zone']['Type']) {
$item['Zone']['Type'] = $something;
}
if (!$item['Zone']['packageA1']) {
!$item['Zone']['packageA1'] = $something;
}
Obviously you need to replace $something with what you actually want to add.
This code could be shortened by the use of ternary operators.
If you are running PHP 5.3 or greater you can do the following:
$item['Zone']['Type'] = $item['Zone']['Type'] ?: $something;
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ?: $something;
Prior to 5.3 you cannot miss out the middle of a ternary operation and have to use the full format as follows:
$value = conditon ? if_true : if_false;
(When using ?: as in my example, 'condition' and 'if_true' take the same value.)
The full ternary operator (for PHP prior to 5.3) would look like:
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ? $item['Zone']['packageA1'] : $something;

$this->$array[$key] returning nothing when there is a value in place

I'm attempting to dynamically use a value in an array within an object.
In my particular case I have an array like this.
$this->customer = array(
[dealerId] => 4
[billFirstName] => Joe
[billLastName] => Blo
[billAddress1] => 1010s
[billAddress2] => 1020s
[billCity] => Anytown
[billState] => ST
[billCountry] => USA
[billPostalCode] => 11111
[dEmail] => emailaddress
[billPhone] => 8008008888
[password] => password
[distPrice] => 5
[distCost] => 20);
$result = $this->keyCheck('dealerId', 'customer');
The method I'm using:
protected function keyCheck($key, $array, $type = false)
{
if(array_key_exists($key, $this->$array) && $this->$array[$key]):
return $this->$array[$key];
else:
return $type;
endif;
}
The first check works (array_key_exists($key, $this->$array)). But the second check fails ($this->$array[$key]) even though there is a value held in that index of the array. I've proven that the array exists inside the keyCheck() method by using, print_r($this->$array); inside the method. And I know the value I'm looking for is available inside the method by using, print $this->$array['dealerId'];
Don't get hung up on the names, or the methodology I'm using, what I'm really interested in is finding out how to address a value held in an array that is dynamically addressed in this way.
It's probably so easy that I'll be slapping my head once it's revealed...
You are running into the dreaded treat string as an array trap, i.e.:
$str = 'customer'; echo $str[0]; // prints c
The $array[$key] portion of $this->$array[$key] is being interpreted as show me the nth index of string $array (if you pass customer it will try to access $this->c, which doesn't exist). Assign the array to a variable first. Here is an example:
class A
{
public $customer = array('dealerId'=>4, 'billFirstName'=>'Joe');
public function keyCheck($key, $arrayName, $type = false)
{
$array = $this->$arrayName;
if(array_key_exists($key, $array) && $array[$key]) {
return $array[$key];
} else {
return $type;
}
}
}
$a = new A();
echo $a->keyCheck('billFirstName', 'customer'); // Joe
Alternatively, you could use the complex syntax: $this->{$arrayName}[$key] as suggested in Artjom's answer.
PHP 5.4 addresses this gotcha:
[In PHP 5.4] Non-numeric string offsets - e.g. $a['foo'] where $a is a
string - now return false on isset() and true on empty(), and produce
a E_WARNING if you try to use them.
This E_WARNING should help developers track down the cause much more quickly.
Well u have to use
$this->{$array}[$key];

In array returning the wrong result

I have the below array..
<?php $arrLayout = array(
"section1" => array(
"wComingEpisodes" => array(
"title" => "Coming Episodes",
"display" => ""
)
));
?>
Then I want to check if wComingEpisodes is in the array so..
<?php if (in_array( "wComingEpisodes" , $arrLayout )) {
echo "CHECKED";}
?>
However its returning nothing even though it is in the array. Do I need to do something different because of the multiple arrays or where is my mistake?
in_array tests for values, not keys. It also does not test nested values.
$arrLayout = array(
"section1" => array(
"wComingEpisodes" => array(
"title" => "Coming Episodes",
"display" => ""
)
));
echo array_key_exists(
"wComingEpisodes",
// this is the array you're actually looking for
$arrLayout['section1'] )?'exists':'does not exist';
you're getting the correct result according to the documentation.
if you want to search an multidimensional array recursive, take a look at the user contributed notes, where you can find examples like this, that show how to do a recursive search (which seems to be what you're looking for).
EDIT:
i just noticed you're trying to find out if a specific key exists: in this case, you'll have to use array_key_exists (like in_array, this also doesn't do a recursive search, so you'll have to do something like this).
in array searches array values.
the string, "wComingEpisodes", is the key of the value
you may want to try using array_key_exists()
In_array isn't recursive by nature so it will only compare the value you give it with the first level of array items of the array you give it.
Thankfully you're not the first with the problem so heres a function that should help you out. Taken from php.net in_array documentation
function in_arrayr($needle, $haystack) {
foreach ($haystack as $v) {
if ($needle == $v) return true;
elseif (is_array($v)) return in_arrayr($needle, $v);
}
return false;
}
http://www.php.net/manual/en/function.in-array.php#60696

Categories