Removing certain elements of array not working - php

i have this array, and all i want it to do is cycle through and just remove certain elements that appear in the if, however whenever i output the array it always just shows
array(0) { }
instead of
["addon_h_id"]=> string(1) "1"
Here is the code which cycles through it, if i remove this code then the array displays as normal
foreach ($new_shopping_array as $columnName => $columnData) {
if($columnName == "s_list_id" || "user_id"){
unset($new_shopping_array[$columnName]);
}
}
Thanks for any and all help

Operator precedence: You're doing $columnName = "s_list_id", then ORing the result of that against "user_id"
if($columnName == "s_list_id" || $columnName == "user_id"){

The problem is your if statement:
if($columnName == "s_list_id" || "user_id")
The string "user_id" will evaluate to true so all values will be removed.
You probably want something like:
if (in_array($columnName, array('s_list_id', 'user_id')))

How about:
$new_array = array();
foreach ($new_shopping_array as $columnName => $columnData)
{
if ($columnName != "s_list_id" && $columnName != "user_id")
{
$new_array[$columnName] = $columnData;
}
}
$new_array contains the data you need.
If you prefer your solution you will need to alter the conditional a bit like so:
foreach ($new_shopping_array as $columnName => $columnData)
{
if ($columnName == "s_list_id" || $columnName == "user_id")
{
unset($new_shopping_array[$columnName]);
}
}
The way it was written it told php that if $columnName is equal to s_list_id OR "user_id". The condition was not in the columnName and "user_id" validates as TRUE (since it has something in there). So your conditional was always TRUE thus removing everything from the original array.
HTH

Related

PHP How to check if array has not key and value

I am using one custom CMS developed by someone and getting issue to check the array result.
The function returns an array of username by passing userids array.
Example Code
$all_users = "1,5,9,10,25,40"; // getting from database
$user_ids = explode(',', $all_users);
$usernames = get_userids_to_usernames($user_ids); //this returns usernames array by passing uesrids array
If the database has not users in the column than the function is returning weird empty / null array as below.
var_dump($usernames);
array(1) { [""]=> NULL }
print_r($usernames);
(
[] =>
)
Now issue is, I want to check if array is empty or has value in return but I have tried everything is_null, empty, count($usernames) > 0 but none of these working.
Can anyone please help me to check conditionally if array has value or empty like above empty result.
Here is a workaround
if (array_key_exists('', $a) && $a[''] === null) {
unset($a['']);
}
then check on emptiness
You can use in_array to check if the array has an empty value and array_key_exists to check the key.
in_array("", $array)
array_key_exists("", $array)
http://php.net/manual/en/function.in-array.php
http://php.net/manual/fr/function.array-key-exists.php
Iterate through array, and check if keys or values are empty or null
$newarray = [];
foreach($array as $key=>$value)
{
if(is_null($value) || trim($value) == '' || is_null($value) || trim($key) == ''){
continue; //skip the item
}
$newarray[$key] = $value;
}
If you want to use empty with it, try array filter
if (empty(array_filter($arr))) {
//Do something
}
Array filter will automatically remove falsey values for you, and you can include a callback should you need more flexability.

PHP - How to append array with some conditions

$list = array(
[0]=> array(
[name]=>'James'
[group]=>''
)
[1]=> array(
[name]=>'Bobby'
[group]=>''
)
)
I am looking to update the item 'group' where the name is 'Bobby'. I am looking for a solution with the two following formats. Thank you in advance for your replies. Cheers. Marc.
array_push($list, ???)
and
$list[] ??? = someting
As far as I know, there's no way updating your array with one of the given syntax.
The only similar thing I can come on is looping over the array using array_walk ... http://www.php.net/manual/en/function.array-walk.php
Example:
array_walk($list, function($val, $key) use(&$list){
if ($val['name'] == 'Bobby') {
// If you'd use $val['group'] here you'd just editing a copy :)
$list[$key]['group'] = "someting";
}
});
EDIT: Example is using anonymous functions which is only possible since PHP 5.3. Documentation offers also ways working with older PHP-versions.
This code may help you:
$listSize = count($list);
for( $i = 0; $i < $listSize; ++$i ) {
if( $list[$i]['name'] == 'Bobby' ) {
$list[$i]['group'] = 'Hai';
}
}
array_push() doesn't really relate to updating a value, it only adds another value to an array.
You cannot have a solution that will fit both formats. The implicit array push $var[] is a syntactic construct, and you cannot invent new ones - certainly not in PHP, and not most (all?) other languages either.
Aside from that, what you are doing is not pushing an item on to the array. For one thing, pushing items implies an indexed array (yours is associative), and for another pushing implies adding a key to the array (the key you want to update already exists).
You can write a function to do it, something like this:
function array_update(&$array, $newData, $where = array(), $strict = FALSE) {
// Check input vars are arrays
if (!is_array($array) || !is_array($newData) || !is_array($where)) return FALSE;
$updated = 0;
foreach ($array as &$item) { // Loop main array
foreach ($where as $key => $val) { // Loop condition array and compare with current item
if (!isset($item[$key]) || (!$strict && $item[$key] != $val) || ($strict && $item[$key] !== $val)) {
continue 2; // if item is not a match, skip to the next one
}
}
// If we get this far, item should be updated
$item = array_merge($item, $newData);
$updated++;
}
return $updated;
}
// Usage
$newData = array(
'group' => '???'
);
$where = array(
'name' => 'Bobby'
);
array_update($list, $newData, $where);
// Input $array and $newData array are required, $where array can be omitted to
// update all items in $array. Supply TRUE to the forth argument to force strict
// typed comparisons when looking for item(s) to update. Multiple keys can be
// supplied in $where to match more than one condition.
// Returns the number of items in the input array that were modified, or FALSE on error.

Search into a multidimensional array

I have imported a CSV to fill a multidimensional array. $arrCSV.
<?php
$foundOneMatchingRow = FALSE;
foreach ($arrCSV as $row) {
if (strpos($row['5'], $val) !== FALSE && strlen($row['5']) > 4) {
$foundOneMatchingRow = TRUE;
echo $row['6'];
}
}
?>
The above code outputs from the value of $val = $_GET['menu']; which is done buy the URL.
I would like to make a search if possible please based on words in $row['6'];.
There will be a search on the page which will pass the search to the URL.
Which would look something like http://example.com/search.php?val=dogs
So the code would look for ANYTHING that relates to dog in $row [6]
I hope I have been clear. Any gudiance would be more than welcome. I am testing everything now.
Thank you
if (strpos($row['6'], $val) !== FALSE) will evaluate to true if $row['6'] contains "dog" (if $val's value is "dog"). That is, will evaluate to true as well if the string in $row['6'] is "bulldog" or "whateverdogwhatever".
BTW, why do you need this condition: strlen($row['5']) > 4? (which I guess should be at least strlen($row['6']) > 4 if you search on $row['6']).
Something else: aren't you confusing strings and integers? Maybe if (strpos($row['6'], $val) !== FALSE) should be if (strpos($row[6], $val) !== FALSE)?
EDIT
I would suggest to define constants for your CSV columns, for readability.
What about for example:
define('CSV_ID', 5);
define('CSV_TEXT', 6);
//...
foreach ($arrCSV as $row) {
if (strpos($row[CSV_TEXT], $val) !== FALSE && strlen($row[CSV_ID]) > 4) {
//...
echo $row[CSV_TEXT];
}
}

How do I remove the nulls out of the inner PHP array

I have an array from which I need to remove null values:
[227] => Array
(
[0] => 3
[1] => 8
[2] =>
[3] =>
[4] => 1
)
)
I tried array_filter($quantity);
and also
foreach ($quantity as $key => $value) {
if (is_null($value) || $value=="") {
unset($quantity);
}
}
and even tried the foreach with $quantity[0] and got Undefined offset 0. Any ideas?
UPDATE
This works but what if i dont have the 227
foreach ($quantityval[227] as $key => $value) {
if (is_null($value) || trim($value)=="") {
unset($quantityval[227][$key]);
}
}
This looks like a nested array -- your foreach statement looks correct, but needs to check the inner arrays:
foreach ($quantity as $key => $item)
foreach ($item as $key2 => $item2) {
if (is_null($item2) || $item2=="") {
unset($quantity[$key][$key2]);
}
}
}
You appear to have values that are all white-space -- either regular spaces or possibly unicode characters. Try trim($value) == "".
If that doesn't work array_filter($array, "is_integer"); may do the trick.
You updated solution works. The part about the hardcoded 227 is because $quantity is a multi-dimensional array (the extra closing parenthesis hinted that too). You need to do nested foreach for that.
foreach($bigArray as $bigKey => $smallArray)
{
foreach($smallArray as $smallKey => $value)
{
if(is_null($value) || $value == "")
unset($bigArray[$bigKey][$smallKey]);
}
}
I use something like this for situations like that:
<?php
function filter_empty_recursive($arr)
{
$keys = array_keys($arr);
foreach($keys as $key)
{
if(is_array($arr[$key]))
{
$arr[$key] = filter_empty_recursive($arr[$key]);
}
else if(empty($arr[$key]))
{
unset($arr[$key]);
}
}
return $arr;
}
It's a recursive function (so it can be a little brutal on memory with large nested array trees, and this particular one cannot handle infinite recursion (i.e.: circular reference).) But with a non-infinite recursion, and reasonably sized nested array trees, it should work pretty well. It can also be expanded to handle nested object properties as well, but that seemed outside scope. The part where it decides if it's empty is that if(empty()) so you can change that back to that is_null or empty string block.
(Edit: Adding really Low level explanation: loops through the array, if it finds an array inside of that array, it calls itself and repeats the process.)

Multidimensional array in foreach

i want to do the foreach only if the content of myformdata[languages1][] is not empty (include zero)
I already try:
foreach((!empty($form['languages1']) as $val){
and
if (!empty($form['languages1'][])) {
foreach($form['languages1'] as $val){
//do stuff
}
i don't have any success. At the moment with the code below the loop is made when the input of myformdata[languages1][] is 0
foreach
foreach($form['languages1'] as $val){
//do stuff
}
thanks
foreach ( $form['languages1'] as $val )
{
// If the value is empty, skip to the next.
if ( empty($val) )
continue;
}
Reference: http://ca.php.net/continue
You're dealing with type coersion
You probably want something like
if(!empty($form['languages1']) && $form['languages1'] !== 0)
So that PHP will match 0 as a number, and not as false.

Categories