was wondering if there's a function to search an array, where the first letter matches a letter chosen. I could do something less elegant like
Loop through array
Each item remove the first character, match to chosen search variable e.g if the first letter from apple, a equals my selection a, show.
Your question is not clear. But below I give you an example of selecting only the selected elements of an array that contain the first letter you want:
function select_from_array($first_letter,$array){
$return = Array();
for($i=0;$i<count($array);$i++){
if($array[$i][0] === $first_letter) $return[] = $array[$i];
}
return $return;
}
Example:
$arr = Array("Nice","Chops","Plot","Club");
print_r(select_from_array('C',$arr));
Result:
Array
(
[0] => Chops
[1] => Club
)
Related
I got array like:
$array = array(
3A32,
4565,
7890,
0012,
A324,
9002,
3200,
345A,
0436
);
Then I need to find which elements has two numbers. The value of number can change.
If values were:
$n1 = 0;
$n2 = 3;
For that search preg_match() should return (3200,0436)
If values were:
$n1 = 0;
$n2 = 0;
preg_match() should return (0012,3200,9002)
Any idea?
Thanks.
I got your logic after looking multiple times on your input array as well as output based on given numbers.
Since i am not good in regular expression at all, i will go to find out answer with commonly know PHP functions.
1.Create a function which takes initial array as well as those search numbers in array form (so that you can search any number and any length of numbers).
2.Now iterate over initial array, split each value to convert to array and do array_count_value() for both split array and numbers array. now apply check and see exact match found or not?
3.Assign this match to a new array declared under the function itself.
4.Return this array at the end of function.
$n1 = 0;
$n2 = 0;
function checkValues($array,$numbers=array()){
$finalArray = [];
if(!empty($numbers)){
foreach($array as $arr){
$splitArr = str_split($arr);
$matched = true;
$count_number_Array = array_count_values($numbers);
$count_split_array = array_count_values($splitArr);
foreach($count_number_Array as $key=>$value){
if(!isset($count_split_array[$key]) || $count_split_array[$key] < $value){
$matched = false;
break;
}
}
if($matched === true){
$finalArray[] = $arr;
}
}
}
return $finalArray;
}
print_r(checkValues($array, array($n1,$n2)));
Output: https://3v4l.org/7uWfC And https://3v4l.org/Tuu5m And https://3v4l.org/fEKTO
Instead of using preg_match, you might use preg_grep and dynamically create a pattern that will match the 2 values in each order using an alternation.
^[A-Z0-9]*0[A-Z0-9]*3[A-Z0-9]*|[A-Z0-9]*3[A-Z0-9]*0[A-Z0-9]*$
The character class [A-Z0-9] matches either a char A-Z or a digit 0-9.
Regex demo | Php demo
If you want to use other characters, you could also take a look at preg_quote to handle regular expression characters.
function getElementWithTwoValues($n1, $n2) {
$pattern = "/^[A-Z0-9]*{$n1}[A-Z0-9]*{$n2}[A-Z0-9]*|[A-Z0-9]*{$n2}[A-Z0-9]*{$n1}[A-Z0-9]*$/";
$array = array(
"3A32",
"4565",
"7890",
"0012",
"A324",
"9002",
"3200",
"345A",
"0436"
);
return preg_grep($pattern, $array);
}
print_r(getElementWithTwoValues(0, 3));
print_r(getElementWithTwoValues(0, 0));
Output
Array
(
[6] => 3200
[8] => 0436
)
Array
(
[3] => 0012
[5] => 9002
[6] => 3200
)
I have an array similar to this:
$stuff = array("a"=>"115","b"=>"0","c"=>"1","d"=>"0","e"=>"11","f"=>"326","g"=>"9","h"=>"1","i"=>"12","j"=>"0","k"=>"56");
What I want to do is concatenate the strings of the keys only where they are consecutive and their values are under 10 - note this includes keeping solitary keys with values under 10 too. I don't need to keep the actual values. In other words, the desired result in this case would be:
Array ( [0] => bcd [1] => gh [2] => j)
So there might be just two consecutive keys that need to be joined, or there might be more (eg as many as 5). I'm not sure how to 'look ahead' through the array to achieve this.
You don't need to look ahead but keep the past in mind.
$consecutive = '';
foreach($stuff as $k => $v) {
if ($v < 10) // or what ever condition you need
$consecutive .= $k;
else {
if ($consecutive) $res[] = $consecutive; // if exist add it
$consecutive= ''; // and reset
}
}
if ($con) $res[] = $con; //adding last element if exist as #Joffrey comment
Now $res will be your desire output
Live example: 3v4l
I have an array which returns something like this:
[44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{
I would like to get all the numbers from the beginning of the string until the first occurrence of a comma in the array element value. In this case that would be number 165 and I want to place that number in another array named $newQuesitons as key questionID
Next part will be to get the string after the first occurrence of : until the next occurrence of : and add it into the same array ($newQuestions) as key question.
Next part will be the photo:, that is I need to get the string after the photo: until the next occurrence of the comma, in this case peace of the string extracted will be c157.
I would like to add that as new key named photo in the array $newQuestions
I think this may be able to help you
<?php
$input = '165,text:Where is this city:,photo:c157,correct:0';
//define our new array
$newQuestions = Array();
//first part states we need to get all the numbers from the beginning of the string until the first occurence of a ',' as this is our array key
//$arrayKey[0] is our arrayKey
$arrayKey = explode(',',$input);
//second part requires us to loop through the array and split up the strings by comma and colon
foreach($arrayKey as $data){
//split each text into 2 by the colon
$item = explode(':',$data);
//we are only interested in items that have a colon in them, if we split it and the input has no colon, the count would be 0, so this check is used to ignore those
if(count($item) > 0) {
//now we can build our array
$newQuestions[$arrayKey[0]][$item[0]] = $item[1];
}
}
//output array
print_r($newQuestions);
?>
I don't fully understand the inputted array so the code above will most likely have to be tweaked, but atleast it gives you some logic to go from.
The output of this was: Array ( [165] => Array ( [165] => [text] => Where is this city [photo] => c157 [correct] => 0 ) )
I get my own solution, at least for the part of the problem. I manage to get the questionID using the following code:
$newQuestions = array();
foreach ($arrQuestions as $key => $question) {
$substring = substr($question, 0, strpos($question, ','));
$newQuestions[]['questionID'] = $substring;
}
I am now trying to do the same thing for the question part. I will update this code in case that someone else may have similar task to accomplish.
I have a challenge that I have not been able to figure out, but it seems like it could be fun and relatively easy for someone who thinks in algorithms...
If my search term has a "?" character in it, it means that it should not care if the preceding character is there (as in regex). But I want my program to print out all the possible results.
A few examples: "tab?le" should print out "table" and "tale". The number of results is always 2 to the power of the number of question marks. As another example: "carn?ati?on" should print out:
caraton
caration
carnaton
carnation
I'm looking for a function that will take in the word with the question marks and output an array with all the results...
Following your example of "carn?ati?on":
You can split the word/string into an array on "?" then the last character of each string in the array will be the optional character:
[0] => carn
[1] => ati
[2] => on
You can then create the two separate possibilities (ie. with and without that last character) for each element in the first array and map these permutations to another array. Note the last element should be ignored for the above transformation since it doesn't apply. I would make it of the form:
[0] => [carn, car]
[1] => [ati, at]
[2] => [on]
Then I would iterate over each element in the sub arrays to compute all the different combinations.
If you get stuck in applying this process just post a comment.
I think a loop like this should work:
$to_process = array("carn?ati?on");
$results = array();
while($item = array_shift($to_process)) {
$pos = strpos($item,"?");
if( $pos === false) {
$results[] = $item;
}
elseif( $pos === 0) {
throw new Exception("A term (".$item.") cannot begin with ?");
}
else {
$to_process[] = substr($item,0,$pos).substr($item,$pos+1);
$to_process[] = substr($item,0,$pos-1).substr($item,$pos+1);
}
}
var_dump($results);
I have an array that contains other arrays of US colleges broken down by the first letter of the alphabet. I've setup a test page so that you can see the array using print_r. That page is:
http://apps.richardmethod.com/Prehealth/Newpublic/test.php
In order to create that array, I used the following code:
$alphabetized = array();
foreach (range('A', 'Z') as $letter) {
// create new array based on letter
$alphabetized[$letter] = array();
// loop through results and add to array
foreach ( $users as $user ) {
$firstletter = substr($user->Schoolname, 0, 1);
if ( $letter == $firstletter ) {
array_unshift( $alphabetized[$letter], $user );
}
}
}
Now, I want to split the array so that a certain range of letters is in each array. For example,
arrayABCEFGH - would contain the schools that begin with the letters A, B, C, D, E, F, G, and H.
My question is, should I modify the code above so that I achieve this before I do one big array, OR should I do it after?
And here is the big question . . if so, how? :-)
Thanks in advance for any help. It's greatly appreciated.
First off, the code to generate the array can be made easier by only iteratating over $users:
$alphabetized = array();
// loop through results and add to array
foreach ($users as $user) {
$firstletter = strtoupper($user->Schoolname[0]);
$alphabetized[$firstletter][] = $user;
}
// sort by first letter (optional)
ksort($alphabetized);
To retrieve the first 8 entries you could use array_slice:
array_slice($alphabetized, 0, 8);
Assuming that all first letters are actually used and you used ksort() on the full array that also gives you from A - H. Otherwise you have to use array_intersect_key() and the flipped range of letters you wish to query on.
array_intersect_key($alphabetized, array_flip(range('A', 'H')));
If you don't need a full copy of the array, then you should encapsulate the above code in a function that has an array as its argument ($letterRange), which will hold the specific array identifiers (letters) to be in the final array.
Then you would need to encapsulate the code within the foreach using an if block:
if (in_array($letter, $letterRange)) { ... }
This would result in an array only containing the letter arrays for the specified letters in $letterRange.
You could write a simple function that takes an array, and an array of keys to extract from that array, and returns an array containing just those keys and their values. A sort of array_slice for non-numeric keys:
function values_at($array, $keys) {
return array_intersect_key($array, array_flip($keys));
}
Which you can then call like this to get what you want out of your alphabetized list:
$arrayABCDEFGH = values_at($alphabetized, range('A','H'));