Compare single array value - php

How can I do a comparison when my array returns value with index.
Returned value is Array ( [isMember] => 0 ) and I want do to a comparison on the value only
if ($memberStatus == 0)
{
print_r($memberStatus);
}

Explanation
Index Array's value can be access by using corresponding index value where as an Associative Array's value can be access by using corresponding key along with array name and in between square brackets that is
arrayName["index-value"]
or
arrayName["key-name"].
You may refer to the following code.
Code
//For Associative Array
$arrayOne = array(
'keyone' => 'a',
'keytwo' => 'b',
'keythird' => 'c'
);
if ($arrayOne['keyone'] == 'a') {
print_r($arrayOne['keyone']);
//output a
}
OR
//For Index Array
$arrayOne = array('a', 'b', 'c');
if ($arrayOne[0] == 'a') {
print_r($arrayOne[0]);
//output a
}

If you have an array like this:
$data = [ 'isMember' => 0, 'data1' => 1, 'data2' => 2 /* ... */ ];
You can access single elements by using the name of the array and write the key in square brackets:
// change isMember to whatever key-value pair you need
$memberStatus = $data['isMember'];
if ($memberStatus === 0)
{
print 'user is a member';
}
else
{
print 'user it not a member';
}

I think what you are looking for is:
$myArray = array(
'isMember' => 0
);
if ( $myArray['isMember'] == 0 ) {
print_r($myArray['isMember']);
}

Are you looking for a key inside an array? Then you need:
echo array_key_exists(9, [1=>'nope',2=>'nope',3=>'nope',9=>'yah']) ? 'Yes it does' : 'it doesn\'t';
Otherwise you are looking for:
echo in_array("my value", ["my value", "a wrong value", "another wrong one"]) ? 'yush' : 'naaaaah';
Either way you can use both in a if statement rather than a thernary operator.

I am not sure which type of array you need to compare because there are generally 2 different types of them:
Indexed
- You pick numerical index which do you want to compare
$array = array("admin", "moderator", "user");
if ($array[0] == "user") {
// CODE
}
Associative
- You pick the string key which do you want to compare
$array = array( "id1" => "member", "id2" => "not member","id3" => "user");
if ($array["id2"] == "not member") {
// CODE
}

Related

PHP comparing all value inside column of multidimensional array with variable

I have a multidimensional array and a variable to compare:
$var = 1;
$arr = array(
0 => array(
'id' => 5
'NumberAssigned' = 1
),
n => array(
'id' => 22
'NumberAssigned' = 1
)
)
I want to compare all of the value inside the NumberAssigned column in the multidimensional array with the variable, if all of the value in column match with the variable then $var = $var+1. What is the solution?
One option is using array_column to make the multidimensional array into a simple array. Use array_unique to get the unique values. If there are only 1 unique value and the value is the same with $var, all NumberAssigned are the same with $var
$var = 1;
$arr = array(
0 => array(
'id' => 5,
'NumberAssigned' => 1
),
1 => array(
'id' => 22,
'NumberAssigned' => 1
),
2 => array(
'id' => 23,
'NumberAssigned' => 1
),
);
$num = array_unique(array_column($arr,'NumberAssigned'));
if( count($num) === 1 && $num[0] === $var ) $var++;
No need to loop.
Use array_column to get all values and remove duplicates with array_unique.
If the var is in the array and the count is 1 then all values match var.
$narr = array_unique(array_column($arr, "NumberAssigned"));
If(in_array($var, $narr) && count($narr) == 1){
$var++;
}Else{
// They are not all 1
}
Echo $var;
https://3v4l.org/k08NI
You can force uniqueness by using the targeted column as first level keys. As a concise technique when you don't need microoptimization, you can use:
if (count(array_column($arr, null, 'NumberAssigned')) < 2)
// true if $arr is empty or all values in column are the same
This won't be technically fastest. The fastest algorithm would allow an early return before iterating the entire set of data in the column.
function allValuesAreSame($array, $columnName) {
$result = [];
foreach ($array as $row) {
$result[$row[$columnName]] = null;
if (count($result) > 1) {
return false;
}
}
return true; // also true if $array is empty
}

Combine post values and remove empty

I have two sets of arrays coming from $_POST. Keys for both will be numeric and the count will be the same, since they come in pairs as names and numbers:
$_POST[names]
(
[0] => First
[1] => Second
[2] =>
[3] => Fourth
)
$_POST[numbers]
(
[0] => 10
[1] =>
[2] => 3
[3] => 3
)
Now I need to combine those two, but remove each entry where either values are missing.
The result should be something like:
$finalArray
(
[First] => 10
[Fourth] => 3
)
Post data is dynamically created so there might be different values missing based on user input.
I tried doing something like:
if (array_key_exists('names', $_POST)) {
$names = array_filter($_POST['names']);
$numbers = array_filter($_POST['numbers']);
if($names and $numbers) {
$final = array_combine($names, $numbers);
}
}
But I can't seem to filter it correctly, since its giving me an error:
Warning: array_combine(): Both parameters should have an equal number of elements
How about using array_filter with ARRAY_FILTER_USE_BOTH flag on?
<?php
$array1 = [
0 => "First",
1 => "Second",
2 => "",
3 => "Fourth",
];
$array2 = [
0 => 10,
1 => "",
2 => 3,
3 => 3,
];
var_dump(array_filter(array_combine($array1, $array2), function($value, $key) {
return $key == "" || $value == "" ? false : $value;
}, ARRAY_FILTER_USE_BOTH ));
/*
Output:
array(2) {
["First"]=>
int(10)
["Fourth"]=>
int(3)
}
*/
Here's a fun way:
$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
$_POST['numbers']))));
// create array using $_POST['names'] as keys and $_POST['numbers'] as values
$result = array_combine($_POST['names'], $_POST['numbers']);
// remove entries that have empty values
$result = array_filter($result);
// remove entry with empty key
unset($result[null]);
print_r($result);
If both arrays will have the same count, and the keys will always be numeric, you could do the following:
$total = count($_POST['names']);
$final = array();
for ($i = 0; $i < $total; $i++) {
if (trim($_POST['names'][$i]) != '' && trim($_POST['numbers'][$i]) != '') {
$final[$_POST['names'][$i]] = $_POST['numbers'][$i];
}
}
Or if you prefer to use a foreach instead of for
$final = array();
foreach ($_POST['names'] as $key => $value) {
if (trim($value) != '' && trim($_POST['numbers'][$key]) != '') {
$final[$value] = $_POST['numbers'][$key];
}
}
Takeing your previous information into account:
both keys will be numeric and the count will be the same, since they come in pairs as names and numbers
$myNewArray = array();
$count = 0;
foreach ($_POST['names'] as $bufferArray)
{
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL))
{
array_push($myNewArray, array($bufferArray[$count] => $_POST['numbers][$count]);
}
$count++;
}
Let me know if that helps! :)
Note: I made some edits to the code.
Also, my previous code checks if the empty array spaces are NULL. If you want to check if they are either NULL or "" (empty), then replace the line of code with:
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL)&&($bufferArray[$count]!="")&&($_POST['numbers][$count]!=""))
{...}

Removing object from array; how to avoid nulls

I have an array that is a object which I carry in session lifeFleetSelectedTrucksList
I also have objects of class fleetUnit
class fleetUnit {
public $idgps_unit = null;
public $serial = null;
}
class lifeFleetSelectedTrucksList {
public $arrayList = array();
}
$listOfTrucks = new lifeFleetSelectedTrucksList(); //this is the array that I carry in session
if (!isset($_SESSION['lifeFleetSelectedTrucksList'])) {
$_SESSION['lifeFleetSelectedTrucksList'] == null; //null the session and add new list to it.
} else {
$listOfTrucks = $_SESSION['lifeFleetSelectedTrucksList'];
}
I use this to remove element from array:
$listOfTrucks = removeElement($listOfTrucks, $serial);
And this is my function that removes the element and returns the array without the element:
function removeElement($listOfTrucks, $remove) {
for ($i = 0; $i < count($listOfTrucks->arrayList); $i++) {
$unit = new fleetUnit();
$unit = $listOfTrucks->arrayList[$i];
if ($unit->serial == $remove) {
unset($listOfTrucks->arrayList[$i]);
break;
} elseif ($unit->serial == '') {
unset($listOfTrucks->arrayList[$i]);
}
}
return $listOfTrucks;
}
Well, it works- element gets removed, but I have array that has bunch of null vaues instead. How do I return the array that contains no null elements? Seems that I am not suing something right.
I think what you mean is that the array keys are not continuous anymore. An array does not have "null values" in PHP, unless you set a value to null.
$array = array('foo', 'bar', 'baz');
// array(0 => 'foo', 1 => 'bar', 2 => 'baz');
unset($array[1]);
// array(0 => 'foo', 2 => 'baz');
Two approaches to this:
Loop over the array using foreach, not a "manual" for loop, then it won't matter what the keys are.
Reset the keys with array_values.
Also, removing trucks from the list should really be a method of $listOfTrucks, like $listOfTrucks->remove($remove). You're already using objects, use them to their full potential!
You can use array_filter
<?php
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
print_r(array_filter($entry));
?>
output:
Array
(
[0] => foo
[2] => -1
)

check if a value exists in array

I am trying this code to check if a value exists in an array.
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo (array_key_exists($num, $arr)); //show the index, in this case 1
}
What i want is show the correspondent value, in other words, 0.58
How can i do that ?
What you need is this:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
Assuming that you have the key or index position of the value you want, there are two functions that you could use, array_key_exists() or isset().
array_key_exists() checks an array to see if the key you specified exists within the array. It does not check to see if there is a value associated with this key. In other words the key may be set in the array, however the value could be null.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
}
isset() can be used to see if a value is set in a specific array index.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$num=3;
if (isset($arr[$num])) {
echo $arr[$num];
}
Since you seem to be asking to only check to see if a specific value exists within an array, you can take a look at using in_array() which will scan the values of the array and return true or false depending on if it found the value.
An example usage:
$arr = array ('2' => '0', '3' => '0.58');
$needle = '0.58';
if (in_array($needle, $arr)) {
echo "found: $needle";
}
Additionally, php.net has a lot of other array functions that you should familiarize yourself with.
var_dump(in_array(0.58, $arr)); // 3
relevant docs.
Try it
<?php
$arr = array(
'2' => '0',
'3' => '0.58'
);
$num = 3;
if (array_key_exists($num, $arr)) {
echo $arr[$num];
// 0.58
}
echo '<br/>';
$val = '0.58';
if (in_array($val, $arr)) {
echo '0.58 found';
}
?>

How to check if a specific value exists at a specific key in any subarray of a multidimensional array?

I need to search a multidimensional array for a specific value in any of the indexed subarrays.
In other words, I need to check a single column of the multidimensional array for a value. If the value exists anywhere in the multidimensional array, I would like to return true otherwise false
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
I would like to know the fastest and most efficient way to check if the array $my_array contains a value with the key "id". For example, if id => 152 anywhere in the multidimensional array, I would like true.
Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.
function whatever($array, $key, $val) {
foreach ($array as $item)
if (isset($item[$key]) && $item[$key] == $val)
return true;
return false;
}
The simplest way is this:
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
if (array_search(152, array_column($my_array, 'id')) !== FALSE) {
echo 'FOUND!';
} else {
echo 'NOT FOUND!';
}
** PHP >= 5.5
simply u can use this
$key = array_search(40489, array_column($userdb, 'uid'));
Let's suppose this multi dimensional array:
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
$key = array_search(40489, array_column($userdb, 'uid'));
Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):
function find_key_value($array, $key, $val)
{
foreach ($array as $item)
{
if (is_array($item) && find_key_value($item, $key, $val)) return true;
if (isset($item[$key]) && $item[$key] == $val) return true;
}
return false;
}
If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:
$lookup_array=array();
foreach($my_array as $arr){
$lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:
echo (isset($lookup_array[152]))?'yes':'no';
A good solution can be one provided by #Elias Van Ootegan in a comment that is:
$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";
I tried it and worked for me, thanks buddy.
Edited
Note: It will work in PHP 5.5+
TMTOWTDI. Here are several solutions in order of complexity.
(Short primer on complexity follows):O(n) or "big o" means worst case scenario where n means the number of elements in the array, and o(n) or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2 or n!. It's more a measure of change in computing time as n increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.
If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.
Solution 0: O(n) / o(1) complexity:
This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.
foreach ($my_array as $sub_array) {
if (#$sub_array['id'] === 152) {
return true;
}
}
return false;
Solution 1: O(n) / o(n) complexity:
This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n iterations thru the array.
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Solution 2: O(n log n) / o(n log n) complexity:
A hash insertion is where the log n comes from; n hash insertions = n * log n. There's a hash lookup at the end which is another log n but it's not included because that's just how discrete math works.
$existence_hash = [];
foreach ($my_array as $sub_array) {
$existence_hash[$sub_array['id']] = true;
}
return #$existence_hash['152'];
I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).
If you want to get a simple true or false output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos to search for the value:
stripos(serialize($my_array),$needle)
It seems to work for me.
As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-
Let say your 2-D array name $my_array and value to find is $id
function idExists($needle='', $haystack=array()){
//now go through each internal array
foreach ($haystack as $item) {
if ($item['id']===$needle) {
return true;
}
}
return false;
}
and to call it:
idExists($id, $my_array);
As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value
I don't know if this is better or worse for performance, but here is an alternative:
$keys = array_map(function($element){return $element['id'];}, $my_array);
$flipped_keys = array_flip($keys);
if(isset($flipped_keys[40489]))
{
// true
}
You can create a queue of sub-arrays and loop each:
function existsKeyValue($myArray, $key, $value) {
$queue = [$myArray]; //creating a queue of a single element, which is our outermost array
//when we reach the count of the queue we looped all inner loops as well and failed to find the item
for ($index = 0; $index < count($queue); $index++) {
//Looping the current array, finding the key and the value
foreach ($queue[$index] as $k => &$v) {
//If they match the search, then we can return true
if (($key === $k) && ($value === $v)) {
return true;
}
//We need to make sure we did not already loop our current array to avoid infinite cycles
if (is_array($v)) $queue[]=$v;
}
}
return false;
}
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
echo var_dump(existsKeyValue($my_array, 'id', 152));
array_column returns the values of a single column of an array and we can search for a specific value for those via in_array
if (in_array(152, array_column($my_array, 'id'))) {
echo 'FOUND!';
} else {
echo 'NOT FOUND!';
}
Try with this below code. It should be working fine for any kind of multidimensional array search.
Here you can see LIVE DEMO EXAMPLE
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ( ($element === $search_for) ){
return true;
}elseif(is_array($element)){
$result = multi_array_search($search_for, $element);
if($result == true)
return true;
}
}
return false;
}
You can use this with only two parameter
function whatever($array, $val) {
foreach ($array as $item)
if (isset($item) && in_array($val,$item))
return 1;
return 0;
}
different between isset vs array_key_exits
What's the difference between isset() and array_key_exists()?
different between == vs === How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
function specificValue(array $array,$key,$val) {
foreach ($array as $item)
if (array_key_exits($item[$key]) && $item[$key] === $val)
return true;
return false;
}
function checkMultiArrayValue($array) {
global $test;
foreach ($array as $key => $item) {
if(!empty($item) && is_array($item)) {
checkMultiArrayValue($item);
}else {
if($item)
$test[$key] = $item;
}
}
return $test;
}
$multiArray = array(
0 => array(
"country" => "",
"price" => 4,
"discount-price" => 0,
),);
$test = checkMultiArrayValue($multiArray);
echo "<pre>"
print_r($test);
Will return array who have index and value
I wrote the following function in order to determine if an multidimensional array partially contains a certain value.
function findKeyValue ($array, $needle, $value, $found = false){
foreach ($array as $key => $item){
// Navigate through the array completely.
if (is_array($item)){
$found = $this->findKeyValue($item, $needle, $value, $found);
}
// If the item is a node, verify if the value of the node contains
// the given search parameter. E.G.: 'value' <=> 'This contains the value'
if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
return true;
}
}
return $found;
}
Call the function like this:
$this->findKeyValue($array, $key, $value);

Categories