Check if a value exists in array (Laravel or Php) - php

I have this array:
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
With a die() + var_dump() this array return me:
array:2 [▼
0 => "hc1wXBL7zCsdfMu"
1 => "dhdsfHddfD"
2 => "otheridshere"
]
I want check if a design_id exists in $list_desings_ids array.
For example:
foreach($general_list_designs as $key_design=>$design) {
#$desing->desing_id return me for example: hc1wXBL7zCsdfMu
if(array_key_exists($design->design_id, $list_desings_ids))
$final_designs[] = $design;
}
But this not works to me, what is the correct way?

You can use in_array for this.
Try
$design_id = 'hc1wXBL7zCsdfMu';
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
if(in_array($design_id, $list_desings_ids))
{
echo "Yes, design_id: $design_id exits in array";
}

instead array_key_exists you just type in_array this will solve your issue
because if you dump your this array
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
output will be,
array(
0 => hc1wXBL7zCsdfMu,
1 => dhdsfHddfD,
2 => otheridshere
)
so your code array_key_exists will not work, because here in keys 0,1,2 exists, So, you want to check values,so for values, just do this in_array it will search for your desire value in your mentioned/created array

you need to change only your condition replace with that code
if(in_array($design->design_id, $list_desings_ids))

Your array not have key .
try this
foreach($general_list_designs as $key_design=>$design) {
#$desing->desing_id return me for example: hc1wXBL7zCsdfMu
if(in_array($design->design_id, $list_desings_ids))
$final_designs[] = $design;
}

use Illuminate\Support\Collection;
First import above class then write below code
$list = new Collection(['hc1wXBL7zCsdfMu', 'dhdsfHddfD', 'otheridshere']);
$id = 'hc1wXBL7zCsdfMu';
if ($list->contains($id)) {
//yes: $id exits in array
}

Related

If key exist into a multidimensional array

I have this array:
$modules = array(
'module1' => array(
'position' => 2
)
);
How I can check that module1 exist and how to get the position number ?
Thanks a lot.
You can use array_key_exists() function
Code
if (array_key_exists("module1", $modules)) {
echo $modules["module1"]["position"]
}
else {
echo "module1 doesn't exist in the array"
}
Hope this helps ;)
To check if a value exists in an array, you can use array_key_exists (value, $ array).
To get the value of this array you must use $array[key][value]. An example is in the case below, where it checks whether the key exists, if it exists prints the value, if there is no exists then print that was not found:
$modules = array(
'module1' => array(
'position' => 2
)
);
$value = 'module1';
if(array_key_exists($value, $modules)) {
echo $modules[$value]['position'];
} else {
echo 'not found';
}
The variable $value may receive the value of you want to fetch. Or you can replace the place where it appears with value you want to fetch.
Use isset function to get it
if(isset($modules['module1']) && isset($modules['module1']['position'])) {
$value = $modules['module1']['position'];
}
Hope this will work
$module['module1']['position']=2;
foreach($module as $index=>$item){
foreach($item as $i){
if($index=='module1'){
echo $i;
}
}
}
Above code help you to determine key value and you can implement your logic arbitrarily

PHP Unset Command in If Statement Not Working

I would like to unset an HTTP Posted key from the array after it echoes the "1" result, but the unset doesn't seem to work. How can I fix this?
$keylist = array('HHH', 'GGG');
if (in_array($_POST["keys"], $keylist)){
echo "1";
unset($keylist[$_POST["keys"]]);
} else {
echo "0" ;
}
Appreciate any help,
Hobbyist
Your unsetting $keylist not $_POST
unset($_POST["keys"]);
You're using the wrong array key for unsetting (You're trying to unset $keylist["HHH"], not, say, $keylist[0]) - you'll need to retrieve the key from the array, and then unset that specifically in order to remove it from the keylist.
$index = array_search($_POST["keys"], $keylist);
if($index!==false) { //YES, NOT DOUBLE EQUALS
unset($keylist[$index));
}
If $_POST["keys"] is an array of keys, you'll need to use array_keys with a search_value instead.
Array_search documentation: http://php.net/manual/en/function.array-search.php
Array_keys documentation: http://php.net/manual/en/function.array-keys.php
EDIT: Adding a full, working example.
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
if(in_array($_POST["keys"], $keylist)) {
$indexToRemove = array_search($_POST["keys"], $keylist);
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Another example, this time checking the index itself to see if it is not false:
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
$indexToRemove = array_search($_POST["keys"], $keylist);
if($indexToRemove!==false) {
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Output:
1Array ( [0] => asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh [1] => derp2 ) Array ( [1] => derp2 )
I realize now that I only had one = on the $index!==false check - the reason you need two is because $index is 0 if you're removing the first element of an array. Per PHP documentation,
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE. Please read the section on Booleans for more
information. Use the === operator for testing the return value of this function.
in_array($_POST["keys"], $keylist) checks if the posted value $_POST["keys"] is present as a value in $keylist, but unset($keylist[$_POST["keys"]]) uses $_POST["keys"] as the key in $keylist to unset something.
Since in_array() returns true, the posted value is present in the array $keylist. But you can't do unset($keylist['GGG']) because that value is not set.
A simple solution is to use the same values as keys too:
$keylist = array('HHH', 'GGG');
$keylist = array_combine($keylist, $keylist);
More about array_combine().
Your array have keys. So "HHH" in keylist is $keylist[0] and not $keylist['HHH']. You can not unset it because you have to define the array key instead of the array value.
Try to search for the array value like this:
array_search($_POST["keys"], $keylist)
This will return the array key for you or false if its not found. Your full code should like look like:
echo "1";
$arrkey = array_search($_POST["keys"], $keylist);
if( $arrkey !== false ){
unset($keylist[$arrkey]);
}
Here the PHP Manual for the array_search function: http://php.net/manual/en/function.array-search.php

How to differentiate a 1-dim array from multi-dim array that have the same count?

I have 2 potential responses arrays, that I am not sure which one will I get.
But I know that it will be one of these following:
1 - might contain array that has key and value
2 - might contain only key and value
My goal is to check to see if my response is falling into one of that category and do my logic base on that.
I tried using PHP count() function, but they both return 2 - which is same value.
What should I check to know what type of response I am getting?
array#1
array:2 [▼
0 => array:2 [▼
"content" => "Administrator"
"XSI:TYPE" => "xs:string"
]
1 => array:2 [▼
"content" => "Read Only"
"XSI:TYPE" => "xs:string"
]
]
array#2
array:2 [▼
"content" => "Read Only"
"XSI:TYPE" => "xs:string"
]
I agree that way that was proposed by cmorrissey in the comments seems best:
since you know the array keys this would be the fastest way to check
if(isset($myArray['content'])){ } else { }
And for a case where you don't know what the array key will be, my previous answer should still work:
Get the first item from the array.
$first = reset($array);
Then count that.
if (count($first) > 1) {
// it's like array 1
} else {
// it's like array 2 ( count($any_string) always returns 1 )
}
You could also use is_array($first). That might be a little faster.
I think this will help you in differentiating between two arrays of same count. You can use COUNT_RECURSIVE flag with count function.
Try this code snippet here
if(count($array1,COUNT_RECURSIVE)==count($array2,COUNT_RECURSIVE))
{
echo "Both's value are strings with equal count";
}
elseif(count($array1,COUNT_RECURSIVE)>count($array2,COUNT_NORMAL))
{
echo "Array one is array of arrays";
}
else
{
echo "Array two is array of arrays";
}
I understand that you need to know if there inside an array exist an other array. I have this posible solution.
We could have an array like this way:
$array = array(1, "string", array(1, 2));
It have an integer, string and an array. We can use gettype() function to get the type of a thing.
In this example:
foreach($array as $row) {
echo gettype($row) . '<br>';
}
We have the next result:
integer
string
array
We can do this:
foreach($array as $row) {
if(gettype($row) == 'array') {
echo "This is an array<br>";
} else {
echo "Keep trying guy...<br>";
}
}
And the result gonna be:
Keep trying guy...
Keep trying guy...
This is an array
I wish this help to you, and remember "Love to code" : )
Not entirely sure I understand the question verbatim, but my initial feeling is you mean to check if the parent array has any child array elements?
In that case, I think you mean?
foreach ($response as $element) {
if (is_array($element)) {
// The element is an array
} else {
// The element is not an array
}
}

Writing PHPUnit Test for a function returning an array

now a days I am playing with PHPUnit. I have gone through its documentation but I am unable to understand it well. Let me explain my case.
I have a function in a class which takes three parameters 1 array, 2 some string, 3 a class object.
This function returns the array by putting second parameter as an index of the array and result as object of that index. My function is as below
public function construct($testArray, $test,$analysisResult) {
$postedTest = explode('_', $test);
$testName = end($postedTest);
$postedTest = implode("_", array_slice($postedTest, 0, -1));
if (in_array($postedTest, array_keys($testArray))) {
$testArray[$postedTest][$testName] = $analysisResult;
} else {
$testArray[$postedTest] = array($testName => $analysisResult);
}
return $testArray;
}
If I call this function like
$constructObj = new Application_Model_ConstructTree();
$test=$this->getMockForAbstractClass('Abstract_Result');
$test->level = "Error";
$test->infoText = "Not Immplemented";
$testArray = Array('databaseschema' => Array('Database' => $test));
$result = $constructObj->construct($testArray,"Database",$test);
The function returns the array like
Array
(
[databaseschema] => Array
(
[Database] => AnalysisResult Object
(
[isRepairable] => 1
[level] => Error
[infoText] => Not Implemented
)
)
)
Now I want to write a PHPUnit Test to check that the attributes of object like isRepairable, level and infoText exists and not empty. I have gone an idea that assertNotEmpty and assertAttributeEmpty can do some thing But I am unable to understand how to do it.
My test looks like
public function testcontruct() {
$constructObj = new Application_Model_ConstructTree();
$test=$this->getMockForAbstractClass('Abstract_Result');
$test->level = "Error";
$test->infoText = "Not Immplemented";
$testArray = Array('databaseschema' => Array('Database' => $test));
$result = $constructObj->construct($testArray,"Database",$test);
$this->assertNotCount(0, $result);
$this->assertNotContains('databaseschema', $result);
}
Can anyone please guide :-)
The last line should be assertContains instead assertNotContains. The next steps in your test would be:
$this->assertContains('Database', $result['databaseschema']);
$this->assertAttributeNotEmpty('isRepairable', $result['databaseschema']['Database']);
$this->assertAttributeNotEmpty('level', $result['databaseschema']['Database']);
$this->assertAttributeNotEmpty('infoText', $result['databaseschema']['Database']);
assertAttributeNotEmpty takes the attribute name and the object as parameters, just as assertContains takes the array key and the array.
I'd use assertArrayHasKey ie:
$this->assertArrayHasKey($key, $array);
Because you need to test a complex structure, what I'd do is going to each one of the expected elements and assert that they are there, and they are not empty with assertNotEmpty()
I found this a good example, similar to your problem:
http://opensourceame.com/asserting-that-an-array-contains-another-array-in-phpunit/

in_array for a combo value ('test','value')

I'm trying to use in_array or something like it for associative or more complex arrays.
This is the normal in_array
in_array('test', array('test', 'exists')); //true
in_array('test', array('not', 'exists')); // false
What I'm trying to search is a pair, like the combination 'test' and 'value'. I can set up the combo to be searched to array('test','value') or 'test'=>'value' as needed. But how can I do this search if the array to be searched is
array('test'=>'value', 'exists'=>'here');
or
array( array('test','value'), array('exists'=>'here') );
if (
array_key_exists('test', $array) && $array['test'] == 'value' // Has test => value
||
in_array(array('test', 'value'), $array) // Has [test, value]
) {
// Found
}
If you want to see if there is a key "test" with a value of "value" then try this:
<?php
$arr = array('key' => 'value', 'key2' => 'value');
if(array_key_exists('key',$arr) && $arr['key'] == 'value'))
echo "It is there!";
else
echo "It isn't there!";
?>
If I understand you correctly, you're looking for a function called array_search()
It accepts a mixed value, so you can even search for objects - I haven't tried it exactly, but it should work for your use case:
if (array_search(array('test','value'), array(array('test','value'),array('nottest','notvalue'))) !== false) {
// item found...
}
ok..
However I think you'll find this method the most useful:
If you just need to find out if a certain key/value pair is located in an array, the easiest way to do it is like this:
<?php
if (isset($arr['key']) && $arr['key'] == 'value') {
// we have a match...
}
?>
if you need to find something in a more complex pattern, there's no avoid creating a bigger loop.
Separate Keys from Values and use in_array()
$myArray = array('test'=>'value', 'exists'=>'here');
array_keys($myArray)
array_values($myArray)

Categories