Exactly one occurence of value in array - php

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";
}

Related

Check if at least one item in a group of items, is not empty

I have this kind of list of variables:
$item[1]['Value']
$item[2]['Value']
...
$item[50]['Value']
Some of them are null.
How do I check if at least one of them is not empty, and in this case, define that one (whether first case or last case) as a new variable?
P.S. What is the name of an $var[number]['foo'] format? Is it an array?
A simple test in using empty() function
if(!empty($item[$i]['value'])
{
echo "exists";
}else{
echo "is not set";
}
If you want affect a new value if it not exists or not defined, you can use null coalescing operator
$item[$i]['value'] = $item[$i]['value'] ?? $newvalue;
to check atleast one of them is not empty
<?php
$atleast=0;//all are empty
for($i=0;$i<count($item);$i++)
{
if(!empty($item[$i]['value']))
$atleast=1;//one is empty;
}
if($atleast==1)
echo "there is more than one element which are not empty";
else
echo "all are emtpy";
?>
This sets the last found used element as newVariable.
for($i = 0; $i < sizeOf($item); i ++)
{
if(isset($item[$i]['Value']))
{
$newVariable = $item[$i]['Variable'];
}
}
If you want to use the inner key as a variable name, then you can check whether you can create it and create it if so:
function any($array) {
foreach ($array as $key => $item) {
if ($item) return $key;
}
return false;
}
$variableName = any($var);
if ($variableName !== false) {
{$variableName} = "yourvalue";
} else {
//We ran out of variable names
}
P.S. The format of $var[number]['foo'] is an array with number keys on the outside and an array with string keys in the inside.
You could array_filter() and use empty() like this :
// example data
$items = [
['Value' => null],
['Value' => 2],
['Value' => null],
];
// remove elements with 'Value' = null
$filtered = array_filter($items, function($a) { return !is_null($a['Value']); }) ;
$element = null;
// If there is some values inside $filtered,
if (!empty($filtered)) {
// get the first element
$element = reset($filtered) ;
// get its value
$element = $element['Value'];
}
if ($element)
echo $element ;
will outputs:
2
array_filter() return an array with non-empty values (using use function).
empty() checks if an array is empty or not.
reset() gets the first element in an array.
If you want to check all the values of all items of the array you can use foreach.
Example:
$item[1]['Value'] = "A";
$item[2]['Value'] = "B";
$item[4]['Value'] = "";
$item[3]['Value'] = NULL;
foreach ($item as $key => $value) {
if (!empty($value['Value'])) {
echo "$key It's not empty \n";
} else {
echo "$key It's empty \n";
}
}
Result:
1 It's not empty
2 It's not empty
3 It's empty
4 It's empty
Also you can see that the empty function consider NULL as empty.
----- EDIT -----
I forget to add the method to detect if at least one item it's empty, you can use:
Example
$item[1]['Value'] = "A";
$item[2]['Value'] = "B";
$item[4]['Value'] = "";
$item[3]['Value'] = NULL;
foreach ($item as $key => $value) {
if (!empty($value['Value'])) {
$item_result = false;
} else {
$item_result = true;
}
}
if ($item_result) {
echo "At least one item is empty";
} else {
echo "All items have data";
}
Result:
At least one item is empty
<?php
$data =
[
1 => ['foo' => ''],
2 => ['bar' => 'big'],
10 => ['foo' => 'fat']
];
$some_foo = function ($data) {
foreach($data as $k => $v)
if(!empty($v['foo'])) return true;
return false;
};
var_dump($some_foo($data));
$data[10]['foo'] = null;
var_dump($some_foo($data));
Output:
bool(true)
bool(false)
Alternatively you can filter foo values that evaluate to false:
$some_foo = (bool) array_filter(array_column($data, 'foo'));

How can check all array keys are include subkey

How can check that all keys are include sub key.
$array1 = array("key1"=>"sub1", "key2"=>"sub2"); // true
$array2 = array("key1", "key2"=>"sub2"); // false
$array3 = array("key1"=>"sub1", "key2"); // false
$array4 = array("key1", "key2"); // false
if(checkSubKey($array1))
echo "true";
else
echo "false";
Thanks so much.
You can also use foreach for this.
$flag=true;
foreach($arr as $key=>$value)
{
if(!($key && $value))
{
$flag= false;
break;
}
}
if($flag==false)
{
//your stuff
}
$array1 = array("key1"=>"sub1", "key2"=>"sub2");
$hasKey = true;
foreach ($array1 as $key => $value)
{
if(!is_string($key))
{
$hasKey = false;
}
}
var_dump($hasKey); //true
$array2 = array("key1", "key2"=>"sub2");
$hasKey = true;
foreach ($array2 as $key => $value)
{
if(!is_string($key))
{
$hasKey = false;
}
}
var_dump($hasKey); //false
This method will work provided you do not assign your own numeric keys. All array positions have an index. If you don't assign one, it will be numerical by default. This method takes advantage of that by assuming that if the array element doesn't have a string-based key, then its key is missing. Although not technically true, it's true enough to satisfy your example.
Try array_key_exists()
Return true if array has key or false if not.
if(array_key_exists("key",$yourarray))
{
echo "exists";
}
{
else "not exist";
}
In order to make sure that a particular key exists in an array, you can make use of php's array_key_exists method:
if (array_key_exists("key1", $array1))
{
echo "Key exists!";
}
You could make use of regular expressions as well, with a little difference though (using preg_match method):
foreach($array1 as $key=> $value){
if(preg_match("/^key/", $key)){ //regular expression
echo "this key exists";
}
}
Alternatively, if you want to determine whether a key holds an array itself (i.e. a sub-array), you could do the following:
foreach($array1 as $a){
if(is_array($a)){
//do some stuff on the inner array
}
}

How to compare two arrays using a for loop?

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 />";
}
}

How to check if a string inside of an array,contains a part of a string in php?

I have this code:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
if(in_array("backup", $arr)){
echo "Da";
} else { echo "Nu";
}
But is not working because,in_array instruction check the array for the complete string "backup" , which doesnt exist.I need to check for a part of the string,for example,to return true because backup is a part of the "Hello_backup" and "Beautiful_backup" strings
EDIT: I take the advice and i have used stripos like this:
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$word='backup';
if(stripos($arr,$word) !== false){
echo "Da";
} else { echo "Nu";}
but now i get an error: "stripos() expects parameter 1 to be string, array given in if(stripos($arr,$word) !== false){"
Use implode to basically concatenate the array values as a string, then use strpos to check for a string within a string.
The first argument you pass to implode is used to separate each value in the array.
$array = array("Hello_backup","World!","Beautiful_backup","Day!");
$r = implode(" ", $array);
if (strpos($r, "backup") !== false) {
echo "found";
}
In this case you need to use stripos(). Example:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$needle = 'backup';
function check($haystack, $needle) {
foreach($haystack as $word) {
if(stripos($word, $needle) !== false) {
return 'Da!'; // if found
}
}
return 'Nu'; // if not found
}
var_dump(check($arr, $needle));
Without a function:
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
$found = false;
foreach($arr as $word) {
if(stripos($word, 'backup') !== false) {
$found = true;
break;
}
}
if($found) {
echo 'Da!';
} else {
echo 'Nu';
}
Try with strpos()
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $v){
echo (strpos($v,"backup")!== false ? "Da" : "Nu");
}
output :- DaNuDaNu
Here is the one line solution for you.
$arr = array("Hello_backup-2014","World!","Beautiful_backup-2014","Day!");
$returned_a = array_map(function($u){ if(stripos($u,'backup') !== false) return "Da"; else return "Nu";}, $arr);
You can use $returned_a with array as your answer..
Array ( [0] => Da [1] => Nu [2] => Da [3] => Nu )
Use this method. It is little bit simple to use.
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
print_r($matches);
Look this working example
According to your question
$matches = preg_grep('/backup/', $arr);
$keys = array_keys($matches);
$matches = trim($matches);
if($matches != '')
{echo "Da";
}else { echo "Nu";}
<?php
$arr = array("Hello_backup","World!","Beautiful_backup","Day!");
foreach($arr as $arr1) {
if (strpos ($arr1,"backup")) {
echo "Da";
} else {
echo "Nu";
}
}
?>

Checking if array is multidimensional or not?

What is the most efficient way to check if an array is a flat array
of primitive values or if it is a multidimensional array?
Is there any way to do this without actually looping through an
array and running is_array() on each of its elements?
Use count() twice; one time in default mode and one time in recursive mode. If the values match, the array is not multidimensional, as a multidimensional array would have a higher recursive count.
if (count($array) == count($array, COUNT_RECURSIVE))
{
echo 'array is not multidimensional';
}
else
{
echo 'array is multidimensional';
}
This option second value mode was added in PHP 4.2.0. From the PHP Docs:
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. count() does not detect infinite recursion.
However this method does not detect array(array()).
The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
is_array($arr[0]);
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
Implicit looping, but we can't shortcircuit as soon as a match is found...
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
For PHP 4.2.0 or newer:
function is_multi($array) {
return (count($array) != count($array, 1));
}
I think this is the most straight forward way and it's state-of-the-art:
function is_multidimensional(array $array) {
return count($array) !== count($array, COUNT_RECURSIVE);
}
After PHP 7 you could simply do:
public function is_multi(array $array):bool
{
return is_array($array[array_key_first($array)]);
}
You could look check is_array() on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.
I think you will find that this function is the simplest, most efficient, and fastest way.
function isMultiArray($a){
foreach($a as $v) if(is_array($v)) return TRUE;
return FALSE;
}
You can test it like this:
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
echo isMultiArray($a) ? 'is multi':'is not multi';
echo '<br />';
echo isMultiArray($b) ? 'is multi':'is not multi';
Don't use COUNT_RECURSIVE
click this site for know why
use rsort and then use isset
function is_multi_array( $arr ) {
rsort( $arr );
return isset( $arr[0] ) && is_array( $arr[0] );
}
//Usage
var_dump( is_multi_array( $some_array ) );
Even this works
is_array(current($array));
If false its a single dimension array if true its a multi dimension array.
current will give you the first element of your array and check if the first element is an array or not by is_array function.
You can also do a simple check like this:
$array = array('yo'=>'dream', 'mydear'=> array('anotherYo'=>'dream'));
$array1 = array('yo'=>'dream', 'mydear'=> 'not_array');
function is_multi_dimensional($array){
$flag = 0;
while(list($k,$value)=each($array)){
if(is_array($value))
$flag = 1;
}
return $flag;
}
echo is_multi_dimensional($array); // returns 1
echo is_multi_dimensional($array1); // returns 0
I think this one is classy (props to another user I don't know his username):
static public function isMulti($array)
{
$result = array_unique(array_map("gettype",$array));
return count($result) == 1 && array_shift($result) == "array";
}
In my case. I stuck in vary strange condition.
1st case = array("data"=> "name");
2nd case = array("data"=> array("name"=>"username","fname"=>"fname"));
But if data has array instead of value then sizeof() or count() function not work for this condition. Then i create custom function to check.
If first index of array have value then it return "only value"
But if index have array instead of value then it return "has array"
I use this way
function is_multi($a) {
foreach ($a as $v) {
if (is_array($v))
{
return "has array";
break;
}
break;
}
return 'only value';
}
Special thanks to Vinko Vrsalovic
Its as simple as
$isMulti = !empty(array_filter($array, function($e) {
return is_array($e);
}));
This function will return int number of array dimensions (stolen from here).
function countdim($array)
{
if (is_array(reset($array)))
$return = countdim(reset($array)) + 1;
else
$return = 1;
return $return;
}
Try as follows
if (count($arrayList) != count($arrayList, COUNT_RECURSIVE))
{
echo 'arrayList is multidimensional';
}else{
echo 'arrayList is no multidimensional';
}
$is_multi_array = array_reduce(array_keys($arr), function ($carry, $key) use ($arr) { return $carry && is_array($arr[$key]); }, true);
Here is a nice one liner. It iterates over every key to check if the value at that key is an array. This will ensure true

Categories