Instead of foreach loop, how can I use in_array()? - php

In codeigniter, in my controller file, I fetch data from model. To validate the results I use foreach loop and there is no problem. But instead of using foreach I want to use in_array() to control if variable is in database result array or not . Here is code :
function _remap($method,$params = array()){
//in construct, I use $this->model
if (isset($params[0])) {
$this->db->distinct('*****');
$this->db->from('*****');
$this->db->where('****',****);
$query = $this->db->get();
if (in_array($params[0],$query->results())) {
echo "in_array works";
}
}
But not echoing anything. How can I do it?Thanks.

According to the manual you could use result_array(). Otherwise you will get back an object. Of course you cannot use in_array for an object.
Also according to the manual you could change your code to
if (in_array($params[0], $query->first_row('array')) {
// ...

The in_array is just to be used for only checking a value in the value-list
e.g. array("Mac", "NT", "Irix", "Linux");
in_array wont work for your situation, because it returns object array.

I would suggest to write a helper method, that does the job you want and returns True or False. Information on how to do it can be found here

Related

PHP: Can't use function return value in write context

Can't use function return value in write context.
All the search result responses say its something to do with the empty function, but I'm not using that?
foreach ($permission as explode(',', $permissionString)) { // line 44
if ($this->hasPermission($permission))
$count++;
}
In a foreach the expression on the left of the as should be the array that you want to iterate through, and the expression on the right is a variable that gets overwritten with the value of each element inside the array.
The reason that you get an error is because php is trying to write an element of $permission into explode(',', $permissionString), but this returns an error because explode(',', $permissionString) is a function call, not a variable, and only variables can be written to.
To fix this, try reversing the order of the as, like this:
foreach (explode(',', $permissionString) as $permission) {

PHP Array Search - key => string

I got some trouble with in_array()
$list = array(
"files/" => "/system/application/files/_index.php",
"misc/chat/" => "/system/application/misc/chat/_index.php"
);
I have this $_GET['f'] which holds the string files/.
How can I search through the array for possible matches?
If the string is found in the array, then the file should be included
Thanks for any help :)
It's really simple. All you need to do is check if the array element is set. The language construct that's usually used is isset() (yes, it's that obvious)...
if (isset($list[$_GET['f']])) {
}
There's no need to call a function for this, isset is cleaner and easier to read (IMHO)...
Note that isset is not actually a function. It's a language construct. That has a few implications:
You can't use isset on the return from a function (isset(foo()) won't work). It will only work on a variable (or a composition of variables such as array accessing or object accessing).
It doesn't have the overhead of a function call, so it's always fast. The overall overhead of a function call is a micro-optimization to worry about, but it's worth mentioning if you're in a tight loop, it can add up.
You can't call isset as a variable function. This won't work:
$func = 'isset';
$func($var);
array_key_exists is a function that returns true of the supplied key is in the array.
if(array_key_exists( $_GET['f'], $list )) {
echo $list[$_GET['f']];
}
You can use in_array() in conjunction with array_keys():
if (in_array($_GET['f'], array_keys($list))) {
// it's in the array
}
array_keys() returns an array of the keys from its input array. Using $list as input, it would produce:
array("files/", "misc/chat/");
Then you use in_array() to search the output from array_keys().
Use array_key_exists.
if(array_key_exists($_GET['f'], $list)){
// Do something with $list[$_GET['f']];
}
in_array() searches array for key using loose comparison unless strict is set.
it's like below.
foreach ($array as $value){
if ($key == $value){
return true;
}
}
My way.
function include_in_array($key, $array)
{
foreach($array as $value){
if ( strpos($value, $key) !== false ){
return false;
}
}
}

how to delete item from an array with filter?

I want to filter and delete an item from an array. is it possible to do it with array_filter() ?
//I want to delete these items from the $arr_codes
$id = 1223;
$pin = 35;
//Before
$arr_codes = Array('1598_9','1223_35','1245_3','1227_11', '1223_56');
//After
$arr_codes = Array('1598_9','1245_3','1227_11', '1223_56');
Thanks!
You can find the index of the value you are interested in with array_search and then unset it.
$i = array_search('1223_35',$arr_codes);
if($i !== false) unset($arr_codes[$i]);
array_filter does not take userdata (parameters). array_walk() does. However, none of the iterator function allow modifying the array structure within the callback.
As such, array_filter() is the appropriate function to use. However, since your comparison data is dynamic (per your comment), you're going to need another way to obtain comparison data. This could be a function, global variable, or build a quick class and set a property.
Here is an example using a function.
array_filter($arr, "my_callback");
function my_callback($val) {
return !in_array($val, get_dynamic_codes());
}
function get_dynamic_codes() {
// returns an array of bad codes, i.e. array('1223_35', '1234_56', ...)
}

PHP: testing for existence of a cell in a multidimensional array

I have an array with numerous dimensions, and I want to test for the existence of a cell.
The below cascaded approach, will be for sure a safe way to do it:
if (array_key_exists($arr, 'dim1Key'))
if (array_key_exists($arr['dim1Key'], 'dim2Key'))
if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))
echo "cell exists";
But is there a simpler way?
I'll go into more details about this:
Can I perform this check in one single statement?
Do I have to use array_key_exist or can I use something like isset? When do I use each and why?
isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like
isset($arr[1][2][3])
is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).
However, if you have
$arr['a'] = null;
then
isset($arr['a']); // false
array_key_exists('a', $arr); // true
comment followup:
Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:
isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.
function recursiveIsset($variable, $checkArray, $i=0) {
$new_var = null;
if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable[$checkArray[$i]];
else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
$new_var = $variable->$checkArray[$i];
if(!isset($new_var))
return false;
else if(count($checkArray) > $i + 1)
return recursiveIsset($new_var, $checkArray, $i+1);
else
return $new_var;
}
Use: For instance
recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))
In my case in drupal this ment for me that the following variable existed
$variables['content']['body']['#object']->body['und']
due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed
$variables->content->body['#object']->body['und']
For a fast one liner you can use has method from this array library:
Arr::has('dim1Key.dim2Key.dim3Key')
Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.
Also, this method will work as expected for null value because it internally uses array_key_exists.
If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.
So yes, there is a simpler way using one single if statement like the following:
if (isset($arr['dim1Key']['dim2Key']) &&
array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
I prefer creating a helper function like the following:
function my_isset_multi( $arr,$keys ){
foreach( $keys as $key ){
if( !isset( $arr[$key] ) ){
return false;
}
$arr = $arr[$key];
}
return $arr;
}
Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.
Imagine you have this kind of array:
$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );
You can write something like this:
$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );
if( $arr ){
//You can use the variable $arr without problems
}
The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.

Sanitizing form data in PHP

Is it possible to sanitize all input sent by one method in PHP by simply doing
$var = mysql_real_escape_string($_POST);
and then access elements of $var as I would have of $_POST ?
I don't think you can call mysql_real_escape_string on an array.
But this would work
$cleanData = array_map('mysql_real_escape_string', $_POST);
array_map works by calling the function named in quotes on every element of the array passed to it and returns a new array as the result.
Like superUntitled, I prefer to have a custom function that uses the built-in sanitizing functions as appropriate. But you could still use a custom function with array_map to achieve the same result.
As a side note, I would recommend using a function to sanitize your results:
function escape($txt) {
if (get_magic_quotes_gpc())
$txt = stripslashes($txt);
if (!is_numeric($txt))
$txt = "'" . mysql_real_escape_string($txt) . "'";
return $txt;
}
this function will remove html tags from anything you pass to it
function strip_html(&$a){
if(is_array($a)){
foreach($a as $k=>$v){
$a[$k]=preg_replace('/<[^<]+?>/','',$v);
}
}else{
$a=preg_replace('/<[^<]+?>/','',$a);
}
return;
}
What I find handy is to encapsulate the request data (Post, Get, Cookie etc) in to an Object and then to add a filter method which u can pass an array of function names to. This way you can use it like this:
$array = array('trim','mysql_real_escape_string');
$request->filter($array);
Body of the method works using a loop an array_map like in Mark's example. I wouldn't run the mysql_real_escape_string over my entire $_POST though, only on the necessary fields ( the ones that are getting queried or inserted )
#Shadow:
Array_Map will work with single dimension array but it wont work with multi-dimension arrays.
So, this will work.
$cleanData = array_map('mysql_real_escape_string', $_POST);
but if that $_POST array were to have another array, like this:
$array = $_POST['myArray']['secondArray'];
If you have an array such as above, array map will throw an error when you try to run a function that only takes a String as an argument, because it wont be handle to an array when its expecting just a string.
The solution provided on the below page is much more handy, and does it recursively for every element inside the array.
PHP -Sanitize values of a array

Categories