I have this code to check some input data to be sure it fits a proper format. However input_28 is a list field that is sent as an array. Is there a shortcut to check each item in the array for the filter instead of looping through each item?
I dont care what it wrong or which line does not match. I just need to know if any line does not match the filter so I can return the form with an error.
if($_POST['input_28'] != filter_var($_POST['input_28'], FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=> "/(\d\d\d\d-\d\d\d\d)|()/" )))){
If I understand correctly, you are looking for array_search(), you can use it like this
if(array_search($value, $array)){
// Do stuff
}
Note that array_search() only works if the array is NOT multi-dimensional, you can take a look on the documentation for more references and examples
Some searching on functions that #Alfonso mentioned in his answer led me to another function: preg_grep That led to this little function which worked great.
$input_28=preg_grep("/^(\d\d\d\d-\d\d\d\d)$/", $_POST['input_28'], PREG_GREP_INVERT);
if(count($input_28) > 0){
#Do Something
}
The PREG_GREP_INVERT makes it return an array of entries that do NOT match the filter. Then we count the array, if any did not match the array will have an entry. Thus greater than 0
Related
I wish to count how many rows in an array has a certain field set to some value (not Null).
Something like: count(isset($names->array_value)).
Is there a command in php for this?
you can check with this code:
if (isset($names['array_value']) && is_array($names['array_value'])){
echo count($names['array_value']);
}
You can use array_filter() and count the result, but since you'll have to write special function for it, simple foreach loop seems like best option to me.
Instead of working with mysql data, I have created csv file that I plan to use as the source of data for content, etc.
And I have successfully been able to parse the csv and store it into a complex array, that has the following header row aka the keys for the arrays.
"Title","Year","Rated","Released","Runtime","Genre","Director","Writer","Actors","Plot","Language","Country","Awards","Poster","Metascore","imdbRating","imdbVotes","imdbID","Type","Response"
My current stage is to allow dynamic ajax sorting of the arrays.
I have two fields, that I am allowing sorting at the beginning, "Year" and "Title".
So I pass different url paramters, such as "yearasc" or "yeardesc" or "titleasc" or "titledesc".
Then try to sort for that.
So what I did reading a different so post, was to do this.
First I create new arrays that only store the key fields, I need for sorting.
Then based on what sort type, do a different array_multisort.
array_multisort($year, SORT_ASC, $all_rows);
But what I get is results that multiple dupplicate data.
But I wonder if having the first row, be the header row, which is required by the function I pass the data after any sorting to, is causing issues with array sorting.
For simple array sorting, existing functions makes sense and work fine.
But for complicated ones, it is just complex to even understand how to approach solving this problem.
Any suggestions, thoughts or ideas are appreciated and thanked.
Thank you!
I don't have the actual code that is probably going to help you, but I do have a suggestion as for how you can tackle this and make it work..
Keep it simple. First, create your own CSV with just 1 header (Year or Title ) that you want to sort on.
Write your code to sort on that.
Then, add the other one ( Title if you used Year before, or Year if you used Title before ) and sort on whichever you want.
Then, add one more header (say, Rated) that you don't want to sort on.
You should then be able to work with the original CSV.
I'd try to write simple methods and keep your processing to a minimum in each one.
I hope that helps. I realize its more philosophical of an answer, so it is hit or miss if it helps you get the job done. Just realize that this approach will, indeed, take a little more time to write - but the point behind it is that you're taking out all of the "noise" that's getting in your way first. It helps you look at only your problem first and solve that.
You can set a custom sort function to the array. Use asort() if you need to keep original array keys.
<?php
$sortfields = array('year', 'bleh');
function cmp($a, $b) {
global $sortfields;
foreach ($sortfields as $sortfield) {
$cmp = strcmp($a[$sortfield], $b[$sortfield]);
// if desc, invert sign of $cmp
if ($cmp !== 0)
return $cmp;
}
return 0;
}
usort($all_rows, "cmp");
The function usort() calls a user defined comparison function, which returns the same logic from strcmp function: 0 if equal, < 0 is $a is less than $b and > 0 if $a is greater than $b.
This function will compare each field set in $sortfields variable, if it find any comparison that is different (in the order set), it will immediately return the difference.
I have a query string. For example:
?filters=1,2,3,4
It gets turned into an array:
$filters = explode(',', $_GET['filters']);
You could push a new value on
$filters = array_push($filters, $new->filter);
Then turn it into the query string
http_build_query($filters);
Or, remove a value
$filters = array_diff($filters, [$new->filter]);
Then turn it into the query string
http_build_query($filters);
I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist. Alternative solutions are also welcome.
Thank you.
Hopefully I'm understanding you correctly "I'm looking for an elegant solution to remove the item if it already exists or to add the item if it does not exist.". Also, not sure if it is elegant but may spark other ideas:
$filters = in_array($new->filter, $filters) ?
array_diff($filters, [$new->filter]) :
array_merge($filters, [$new->filter]);
That's about as elegant as it gets, unless you want to use PHP's array notation "hack", e.g.
?filters[]=1&filters[]=2&filters[]=3&etc...
^^---
That'd save you the explode() stage and gives you the ability to treat $_GET['filters'] as an array directly, but at the cost of an uglier/longer URL.
Perhaps you should write 2 functions, "remove" and "add", which would each loop through the array looking for the value in question. Then the remove function could remove it, and the add function could add it. The functions themselves would not be so elegant, but using them would be simple elsewhere in your code.
I feel stupid for asking this cause it seems so basic but it's really bugging me.
I have a method that returns an array with a single element. I just want it to return the element not wrapped in an array. I tried this.
return $f->getValue()[0];
and it gives an error but if I save it to a variable, it works fine.
$v = $f->getValue();
return $v[0];
I can't figure it out....
It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o
What you are trying to do, is called array dereferencing, and is only possible in PHP as of version 5.4 (if you scroll up a few lines in the documentation article I linked to, you'll see it mentioned).
Use reset().
<?php return reset( $f->getValue() ); ?>
Edit: reset() is probably superior to current() as it also makes sure that the internal pointer is reset, despite it not making much difference if the array only contains one element.
As far as I know since you are returning an array you only can get an array. You can instead save the array to a variable in the class (accessible by $f->myArray) and then return just the string portion. Or the other option is to do what your second example is and return the array and retrieve the string from it.
have you tried this
<?php
return array_shift(array_values($array));
?>
Get the first element of an array
I have this situation in PHP. I have an array that has these keys for example, wires-1, wires-2, wires-3. I need a function or way for my program to read these keys, and find that the common word is wires? How would that be accomplished in PHP? Thanks for your help.
Take a look at how an autocomplete's functionality works, this is similar to your approach.
I'm sure there's plenty of source codes for autocomplete on google
For the string value of every key in your array:
Throw away all non-alpha characters, i.e. leave only letters such that ctype_alpha($remaining_text) should return true.
Keep an array with the found words as keys, and their frequencies as values, as such:
$array = new array();
function found_word($word)
{ global $array;
if(!isset($array[$word])) { $array[$word] = 1; }
else { $array[$word]++; }
}
Only nicer ;)
Sort the array in reverse by using arsort($array);
$array now contains the most found words as its first elements.
you would have to create every possible suffix of every string you have.
create a map for every suffix you found
count the occurence of every suffix in your string array
you can modify the performance with f.ex. limiting the suffix length