I have array as follows,
$arr['fixed_key'][0]['key1']['key2'] = 'y';
$arr['fixed_key'][1]['key1']['key2'] = 'y';
$arr['fixed_key'][2]['key1']['key2'] = 'n';
$arr['fixed_key'][3]['key1']['key2'] = 'n';
I want to remove all arrays which have key2='n', I can traverse through array in a loop and achieve this, as follows:
$l=length($arr);
for($i=0;$i<$l;$i++) {
if($arr['fixed_key'][$i]['key1']['key2'] == 'n') {
unset($arr['fixed_key'][$i]['key1']['key2']);
}
}
My question is, is it possible to do this in better way, like array_map or array_walk, what is the best possible way?
You can use array_filter
$arr['fixed_key'][0]['key1']['key2'] = 'y';
$arr['fixed_key'][1]['key1']['key2'] = 'y';
$arr['fixed_key'][2]['key1']['key2'] = 'n';
$arr['fixed_key'][3]['key1']['key2'] = 'n';
$filtered = array_filter($arr['fixed_key'], function ($val) { return $val['key1']['key2'] !== "n"; });
We can achive by using array_search() and unset, try the following:
if(($key = array_search($del_value, $arr)) !== false) {
unset($arr[$key]);
}
Related
I have created method to sort array with values like this: array('regdate','birthday','editdate') which should sort the elements in the way that the elements containing word date should be moved to left like this array('regdate','editdate','birthday')
public function sortColumnsBySubstring($haystack, $substr){
if ($haystack == $substr) {
return 0;
}
return strpos($substr) !== false ? -1 : 1;
}
However it is not clear to me how to make this working. Example which I have found in php manual shows function with no arguments or closures - I use php version 5.2 so I cannot use closures.
All I can think up is this usort($date_cols, $this->sortColumnsBySubstring($value, 'date') but here $value is undefined so it's not solution.
Question is how to implement the function to work correctly?
You need to pass the callback as an array:
usort($date_cols, [$this, 'sortColumnsBySubstring']);
See Callbacks / Callables in PHP docs.
First solution is to my original question:
function cmp($a, $b)
{
$adate = (strpos($a, 'date') !== false);
$bdate = (strpos($b, 'date') !== false);
if (!($adate ^ $bdate)) return strcmp($a, $b);
return $adate ? -1 : 1;
}
$a = array('birthday', 'regdate', 'editdate');
usort($a, 'cmp');
Second solution uses splitting into two arrays, sort and then merge them back. I have tried to use more word related to time to identify the values related to time.
private function getDateColumns(&$array)
{
$search_date_columns = array('date','datetime','timestamp','time','edited','changed','modified','created','datum');
$result = array( array(), array() );
foreach($array as $v1):
$found = false;
foreach($search_date_columns as $v2)
if ( strpos($v1, $v2)!==false )
{ $found = true; break; }
if ($found)
$result[0][] = $v1;
else
$result[1][] = $v1;
endforeach;
return $result;
}
Which is implemented like that:
$date_cols = array('regdate','time','editdate','createdate','personal','mojedatum','edited','test','modified','changed','pokus','timestamp','hlava');
$arrays = $this->getDateColumns($date_cols);
rsort($arrays[0]);
$date_cols = array_merge($arrays[0], $arrays[1]);
unset($arrays);
print_r($date_cols);
I am stuck. What I would like to do: In the $description string I would like to check if any of the values in the different arrays can be found. If any of the values match, I need to know which one per array. I am thinking that I need to do a function for each $a, $b and $c, but how, I don't know
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$a = array('1:100','1:250','1:10','2');
$a = getExtractedValue($a,$description);
$b = array('one','five','12');
$b = getExtractedValue($b,$description);
$c = array('6000','8000','500');
$c = getExtractedValue($c,$description);
}
}
}
function getExtractedValue($a,$description){
?
}
I would be very very greatful if anyone could help me with this.
many thanks Linda
It would be better to create each array just once and not in every iteration of the while loop.
Also using the same variable names in the loop is not recommended.
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
$a = array('1:100','1:250','1:10','2');
$b = array('one','five','12');
$c = array('6000','8000','500');
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$aMatch = getExtractedValue($a,$description);
$bMatch = getExtractedValue($b,$description);
$cMatch = getExtractedValue($c,$description);
}
}
}
Use strpos to find if the string exists (or stripos for case insensitive searches). See http://php.net/strpos. If the string exists it will return the matching value in the array:
function getExtractedValue($a,$description) {
foreach($a as $value) {
if (strpos($description, $value) !== false) {
return $value;
}
}
return false;
}
there s a php function for that which return a boolean.
or if you wanna check if one of the element in arrays is present in description, maybe you 'll need to iterate on them
foreach($array as element){
if(preg_match("#".$element."#", $description){
echo "found";
}
}
If your question is correctly phrased and indeed you are searching a string, you should try something like this:
function getExtractedValue($a, $description) {
$results = array();
foreach($a as $array_item) {
if (strpos($array_item, $description) !== FALSE) {
$results[] = $array_item;
}
}
return $results;
}
The function will return an array of the matched phrases from the string.
Try This..
if ( in_array ( $str , $array ) ) {
echo 'It exists'; } else {
echo 'Does not exist'; }
I would like to assign a variable that is the first not null element from another set of variables. Much like the conditional assignment in ruby ||=. For example:
<?php
$result = null;
$possibleValue1 = null;
// $possibleValue2 not defined
$possibleValue3 = 'value3';
if (isset($possibleValue1) && !is_null($possibleValue1)) {
$result = $possibleValue1;
} else if (isset($possibleValue2) && !is_null($possibleValue2)) {
$result = $possibleValue2;
} else if (isset($possibleValue3) && !is_null($possibleValue3)) {
$result = $possibleValue3;
}
Is there a way to do this simply in php, like so (if possible, I would like to avoid creating a function and just use functions from the php library):
$result = firstNotNull(array($possibleValue1, $possibleValue2, $possibleValue3));
I think the shortest way is:
$result = current(array_filter(array($possibleValue1, $possibleValue2, $possibleValue3)));
If all $possibleValues are definitely set:
$possibleValues = array($possibleValue1, $possibleValue2, ...);
If they may not be set:
$possibleValues = compact('possibleValue1', 'possibleValue2', ...);
Then:
$result = reset(array_filter($possibleValues, function ($i) { return $i !== null; }));
Do not know about such a function in PHP but why not creating Your own?
function getFirstNotNullValue($values = array()) {
foreach($values as $val)
if($val) return $val;
return false;
}
I have a string which may or may not contain commas. If it does, I want it exploded into an array; if it doesn't, I still want the string saved to the new identifier. My code clearly doesn't work. Anyone have any better ideas?
if(explode(",", $_SESSION['shoparea']))
{
$areas = explode(",", $_SESSION['shoparea']);
} else {
$areas = $_SESSION['shoparea'];
}
What is the correct syntax for this operation?
if(strpos($_SESSION['shoparea'], ',') !== false) {
$areas = explode(',', $_SESSION['shoparea']);
} else {
$areas = $_SESSION['shoparea'];
}
Everything can be exploded, if there are no instances of the delimiter it becomes a singleton array, so it may be simpler to do
$result = explode(",", $_SESSION['shoparea']);
if (count($result) == 1)
$areas = $result[0];
else
$areas = $result;
You could use http://php.net/strpos function to ensure that ',' are present.
you could do this for examle
$areas = $_SESSION['shoparea'];
if(strpos($areas, ',') !== false) {
$areas = explode(",", $areas);
}
All you need is
$_SESSION['shoparea'] = "xx"; // Test value ..
if (!$areas = explode(",", $_SESSION['shoparea'])) {
$areas = array($_SESSION['shoparea']);
}
Output
array
0 => string 'xx' (length=2)
Note : $areas needs to always be array .. if you are using a loop you might have issue so i converted it ..
if (substr_count($_SESSION['shoparea'], ',') > 0) {
$areas = explode(",", $_SESSION['shoparea']);
}
else {
$areas = $_SESSION['shoparea'];
}
i have an array like this
Array ([0]=>'some values'[1]=>'')
I want to change the empty elemnt of an array to a value of 5
how can I do that
thanks
5.3 version
$arr = array_map(function($n) { return !empty($n) ? $n : 5; }, $arr);
If you know at which position it is, just do:
$array[1] = 5;
If not, loop through it and check with === for value and type equality:
foreach($array as &$element) { //get element as a reference so we can change it
if($element === '') { // check for value AND type
$element = 5;
}
}
You can use array_map for this:
function emptyToFive($value) {
return empty($value) ? 5 : $value;
}
$arr = array_map(emptyToFive, $arr);
As of PHP 5.3, you can do:
$func = function($value) {
return empty($value) ? 5 : $value;
};
$arr = array_map($func, $arr);
EDIT: If empty does not fit your requirements, you should perhaps change the condition to $value === '' as per #Felix's suggestion.
This $array[1] = 5;