If I have an array:
Array
(
[0] =>
[1] => a
[2] => b
[3] => c
)
And I want to get the first non-null value from the array, in this case "a". How could I go about doing that nice and easily?
Not sure about nice and easy. But a short approach might be:
$first = current(array_filter($sparse_array));
Where array_filter will extract you the "truthy" values, thus skipping empty and false entries. While current simply gives you the first of those remaining entries.
function get_first_not_null($array){
foreach($array as $v){
if($v !== null){
return $v;
}
}
return null;
}
function getFirstNotNull($array) {
foreach($array as $val) {
if(!is_null($val) || !$val) return $val;
}
}
$res = null;
foreach ($arr as $v) {
if ($v !== null) {
$res = $v;
break;
}
}
Well, you could try this:
foreach($array as $x) {
if( $x) break;
}
if( $x) {
// $x is the first non-null value
}
else {
// There were no non-null values
}
I would use array_reduce
$firstNonNull = array_reduce($array, function($v, $w) {
return $v ? $v : (isset($w) ? $w : FALSE);
});
Related
I got an Array:
$myArrays = array(5,4,3,2,1);
foreach($myArrays as $myArray)
{
echo $myArray;
$val = 3;
if($myArray == $val)
{
break;
}
}
Output: 5,4,3
I would want it to be like
output: 3,2,1
is this possible?
You can use the following snippet.
The first element of array is always the left one, when you define it.
<?php
foreach($myArrays as $myArray)
{
if ($myArray <= 3) {
echo $myArray;
}
}
$myArrays = array(5,4,3,2,1);
foreach($myArrays as $myArray)
{
$val = 3;
if($myArray > $val)
{
continue;
}
echo $myArray;
}
Simply have a boolean variable outside loop to keep track of wheter you got the element you're looking for.
Skip the loop (By using continue keyword) until you find that element.
So your will look something like this,
$foundelement=false;
foreach($myArrays as $myArray)
{
$val = 3;
if(!$foundelement && $myArray != $val)
{
continue;
} else {
$foundelement=true;
}
if($foundelement) {
echo $myArray;
}
}
Demo: https://eval.in/620081
I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.
I have an array like the following:
5-9-21,
5-10-22,
5-10-22,
5-11-23,
3-17-29,
3-19-31,
3-19-31,
1-25-31,
7-30-31
I wil get a value dynamically. Then I have to compare that value with the middle part of array.
9,
10,
10,
11,
17,
19,
19,
25,
30
If it's matching then I have to remove the whole part from array.
For example. If I am getting a value dynamically is 19, then I wil match with that array. And 3-19-31 is there two times. So it will remove all 3-19-31. After exploding with "-".
How can I do this?
foreach($array as $key=>$value){
$parts = explode('-', $value);
if($parts[1] == $search) {
unset($array[$key]);
}
}
Or if your search is an array
foreach($array as $key=>$value){
$parts = explode('-', $value);
if(in_array($parts[1], $search)) {
unset($array[$key]);
}
}
You could use array_filter to get a new array.
$new_arr = array_filter($old_arr, function($var) use ($input) {
$ret = explode('-', $var);
return !(isset($ret[1]) && $ret[1] === $input);
});
Or use a normal loop and then use unset to remove the values.
for ($arr as $key => $value) {
$ret = explode('-', $value);
if (isset($ret[1]) && $ret[1] === $input) {
unset($arr[$key]);
}
}
use this function, this will give you all the keys which are matched:
function custom_array_search($keyword,$array){
if(!is_array($array)){
return false;
}
$ret_keys = array();
foreach($array as $key=>$value){
if(strpos("-{$keyword}-",$value)!==false){
$ret_keys[] = $key;
}
}
return $ret_keys;
}
This function will give you all keys in an array.
Now you can delete those i.e. unset all keys from that array. :)
<?php
$arr = array('5-9-21', '5-10-22', '5-10-22', '5-11-23', '3-17-29', '3-19-31', '3-19-31', '1-25-31', '7-30-31');
$k = '10';
#print_r($arr);
foreach ($arr as $key => $value)
{
$t = explode('-',$value);
if($t[1] == $k)
{
unset($arr[$key]);
#echo "deleted<br>";
}
}
#print_r($arr);
?>
You can try this...
$arr; // your array
$value = 19;
foreach ($arr as $key=>$a)
{
if(strpos($a, "-".$value."-") !== false)
unset($arr[$key]);
}
There are few ways you can do this. If you are going to have only one digit always in the first eliment of your triplet, the following code should work;
$triplet_array = array(5-9-21, 5-10-22, 5-10-22, 5-11-23, 3-17-29, 3-19-31, 3-19-31, 1-25-31, 7-30-31);
$i = 0;
foreach($triplet_array as triplet){
$middle = substring($triplet,2,0);
if($middle == $my_dynamic_value) unset($triplet_array[$i]);
$i++
}
but, if the first part is not going to contain only one digit always;
foreach($triplet_array as triplet){
$this_triplet = explode('-',$triplet);
if($this_triplet[1] == $my_dynamic_value) unset($triplet_array[$i]);
$i++
}
hope this helps :-)
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
From the above array i need the value Dog alone. how can i get the unique value from an array?. is there any functions in php?...
Thanks
Ravi
Have a look at:
http://php.net/function.array-unique
and maybe:
http://php.net/function.array-count-values
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$counted = array_count_values($a);
$result = array();
foreach($counted as $key => $value) {
if($value === 1) {
$result[] = $key;
}
}
//$result is now an array of only the unique values of $a
print_r($result);
function getArrayItemByValue($search, $array) {
// without any validation and cheking, plain and simple
foreach($array as $key => $value) {
if($search === $value) {
return $key;
}
}
return false;
}
then try using it:
echo $a[getArrayitembyValue('Dog', $a)];
Try with:
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$aFlip = array_flip($a);
$unique = array();
foreach ( array_count_values( $a ) as $key => $count ) {
if ( $count > 1 ) continue;
// $unique[ array_search($key) ] = $key;
$unique[ $aFlip[$key] ] = $key;
}
Use following function seems to be working & handy.
<?php
$array1 = array('foo', 'bar', 'xyzzy', 'xyzzy', 'xyzzy');
$dup = array_unique(array_diff_assoc($array1, array_unique($array1)));
$result = array_diff($array1, $dup);
print_r($result);
?>
You can see its working here - http://codepad.org/Uu21y6jf
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$result = array_unique(a);
print_r($result);
try this one...
What's the best way to remove the parent of a matched key in an Multidimensional Array? For example, let's assume we have the following array and I want to find "[text] = a" and then delete its parent array [0]...
(array) Array
(
[0] => Array
(
[text] => a
[height] => 30
)
[1] => Array
(
[text] => k
[height] => 30
)
)
Here’s the obvious:
foreach ($array as $key => $item) {
if ($item['text'] === 'a') {
unset($array[$key]);
}
}
using array_filter:
function filter_callback($v) {
return !isset($v['text']) || $v['text'] !== 'a';
}
$array = array_filter($array, 'filter_callback');
this will only leave 'parent elements' in the array where text != a, therefore deleting those where text equals a
The inner arrays don't maintain any reference to their "parent" arrays, so you'd have to write a function to manually track this. Something like this might work:
function searchAndDestroy(&$arr, $needle) {
foreach ($arr as &$item) {
if (is_array($item)) {
if (searchAndDestroy($item, $needle)) {
return true;
}
} else if ($item === $needle) {
$item = null;
return true;
}
}
}
Note that this is designed to work at any level of nesting, not just two dimensions, so it might be a bit of overkill if you only need it for situations like in your example.
A simple and safe solution(I'd not remove/unset elements from an array I'm looping through) could be:
$new_array = array();
foreach($array as $item)
{
if($item['text'] != "a")
{
$new_array[] = $item;
}
}
My implementation:
function searchAndDestroy(&$a, $key, $val){
foreach($a as $k => &$v){
if(is_array($v)){
$r = searchAndDestroy(&$v, $key, $val);
if($r){
unset($a[$k]);
}
}elseif($key == $k && $val == $v){
return true;
}
}
return false;
}
searchAndDestroy($arr, 'text', 'a');
To test it:
<pre><?php
function searchAndDestroy(&$a, $key, $val){
foreach($a as $k => &$v){
if(is_array($v)){
$r = searchAndDestroy(&$v, $key, $val);
if($r){
unset($a[$k]);
}
}elseif($key == $k && $val == $v){
return true;
}
}
return false;
}
$arr = array(array('text'=>'a','height'=>'30'),array('text'=>'k','height'=>array('text'=>'a','height'=>'20')));
var_dump($arr);
searchAndDestroy($arr, 'text', 'a');
var_dump($arr);
?></pre>
This function does it recursively.