Explode long string - PHP - php

I have a long string like: B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5, and i need to explode it on pairs so in this case 1 - B1 2 - C1 and so on...
The reason why i need that is that each pair contains 1 information in database so i have to take each of that pair and make some cycle or something to MySQL search
I was thinking about convert that sting to array like this:
1=> B1
2=> C1
3=> F4
and then foreach that with something like
foreach ($array as $arr)
{
//and here come database search
}
But maybe i am completly wrong and to say true everything i try finish with ERROR so guys i am up for any advise, if somebody have time to write an example code it will be awesome.
Thanks!
p.s.
First of all i was thinking about something like:
$string[0] = substr($string,0,2);
$string[1] = substr($string,2,4);
but string will changing and I never know how long it will be

You can use str_split()
$str = 'B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5';
$ar = str_split($str,2);
print_r($ar);
Make sure you access the first element with zero index.

You can always access a string like an array in itself without having to do anything to it like this:
$string='B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5';
for($i=0;$i<strlen($string)/2;$i++)
{
$arr[]=$string[$i*2].$string[($i*2)+1];
}
print_r($arr);

Php function str_split might work
>>> $text = 'B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5'
>>> str_split($text, 2)
=> [
"B1",
"C1",
"F4",
"G6",
"H4",
"I7",
"J1",
"J8",
"L5",
"O6",
"P2",
"Q1",
"R6",
"T5",
"U8",
"V1",
"Z5"
]

You should use recursion:
$string = "B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5";
$array = recursion($string);
print_r($array);
function recursion ($string, $array = array()){
if (strlen($string) < 1){
return $array;
}else{
$array[] = substr($string, 0 ,2);
return recursion(substr($string, 2), $array);
}
}

Related

PHP Using the array_filter

I will try to explain my situation as best as possible so bear with me.
I have an array with single words in them, for example:
This
is
a
test
array
Now i created another array that looks alike but with 2 words, which looks like this:
This is
is a
a test
test array
Ok here is where my problem starts. I have an array of 'common words' those words should be exluded from the array. Let's say those common words would be is and a for this example. Right now i search for common words first on the single word array so i can use if(in_array($word, $common_words)) continue; Which makes it skip the one if it's in the common_words array.
But this would result in this array:
This test
test array
But this is not how i want it to happen. It should be like this:
test array
Because this is the only 1 that had these 2 words next to eachother originally before we started to take out the 'common_words'. (are you still with me?)
The problem here is that if(in_array) doesn't work anymore if I have an array with 2 words. So i did some research and stumbled upon the array_filter command. I think this is what I need but i'm at a total loss as on how to use/apply it to my code.
I hope I explained it well enough for you to understand what my problem is and I would appreciate it if someone could help me.
Thanks in advance!
Your guess is correct, you can use:
$array = ['this is', 'array array', 'an array', 'test array'];
$stop = ['is', 'test'];
$array = array_filter($array, function($x) use ($stop)
{
return !preg_match('/('.join(')|(', $stop).')/', $x);
});
-i.e. exclude all items with certain words in it by pattern using array_filter()
This will work with filtering because it will match by regex, i.e. from $stop we'll get regex (is)|(test)
A good idea will be to evaluate regex separately so do not evaluate it each time inside array_filter() iteration, like:
$array = ['this is', 'array array', 'an array', 'test array'];
$stop = ['is', 'test'];
$pattern = '/('.join(')|(', $stop).')/';
$array = array_filter($array, function($x) use ($pattern)
{
return !preg_match($pattern, $x);
});
Important note#1: if your stop words may contain some special characters that will be treated in regex in special way, it's needed to use preg_quote() like:
$pattern = '/'.join('|', array_map(function($x)
{
return '('.preg_quote($x, '/').')';
}, $stop)).'/';
$array = array_filter($array, function($x) use ($pattern)
{
return !preg_match($pattern, $x);
});
Important note#2: If your array of stopwords is too long this may cause regex compilation fail because of it's length (too large). There are some tricks to overcome it, but if it's your case, you'd better to use strpos() instead:
$array = array_filter($array, function($x) use ($stop)
{
foreach($stop as $word)
{
if(false!==strpos($x, $word))
{
return false;
}
}
return true;
});
I think, the bes way, two operators: array_diff and array_unique
$a[] = 'This';
$a[] = 'is';
$a[] = 'is';
$a[] = 'a';
$a[] = 'a';
$a[] = 'test';
$a[] = 'test';
$a[] = 'array';
$excluded = array('is', 'a');
$result = array_diff($a, $excluded); // Remove all excluded words
$result = array_unique($result); // unique values
var_dump($result);
And result:
array (size=3)
0 => string 'This' (length=4)
5 => string 'test' (length=4)
7 => string 'array' (length=5)

Issues with in_array

I have the following fairly simple code, where I need to determine if a certain value exists in an array:
$testvalue = $_GET['testvalue']; // 4
$list = '3, 4, 5';
$array = array($list);
if (in_array($testvalue, $array)) { // Code if found } else { // Code if not found }
Even though it is obvious that the number 4 is in the array, the code returns the code inside the else bracets. What have I done wrong?
Change the third line:
$array = array_map('trim', explode(',',$list));
$array here is:
$array = array('3, 4, 5');
which is not the same as:
$array = array(3, 4, 5);
So, fix the way you are creating this array.. don't do it from a string.
Your array contains just one value, the string 3, 4, 5.
See the example on CodePad.
If you want to convert your string in an array, you can use:
$array = explode(', ', $list);
I have added a space behind the comma, but a safer method would be to use just a comma and then trim all values.

Finding position of data in the array - PHP

I have a PHP array, say,
$array = Array("Name1","Name2","Name3","Name4","Name5");
I want to find the position of these names in the array.
I want to return 0 for Name1 and 2 for Name3.
How can I do this?
Do you mean:
$key = array_search('Name1', $array);
Ref: array_search
$pos = array_search("Name3", $array);
Should be what you are looking for, note that to be safe, result checking should be using === (three equal signs) so that those returning 0 (if you are looking for thing in the first element) is also checked for type when you are comparing them in an if statement
if(array_search($name, $array) === 0)
Something like that:
<?php
$array = Array("Name1", "Name2", "Name3", "Name4", "Name5");
$searchValue = "Name1";
$keys = array_keys($array, $searchValue);
// test it
print_r($keys);
?>

PHP - Get array value with a numeric index

I have an array like:
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
echo native_function($array, 0); // bar
echo native_function($array, 1); // bin
echo native_function($array, 2); // ipsum
So, this native function would return a value based on a numeric index (second arg), ignoring assoc keys, looking for the real position in array.
Are there any native function to do that in PHP or should I write it?
Thanks
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum
array_values() will do pretty much what you want:
$numeric_indexed_array = array_values($your_array);
// $numeric_indexed_array = array('bar', 'bin', 'ipsum');
print($numeric_indexed_array[0]); // bar
I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function.
In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.
So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].
function array_get_by_index($index, $array) {
$i=0;
foreach ($array as $value) {
if($i==$index) {
return $value;
}
$i++;
}
// may be $index exceedes size of $array. In this case NULL is returned.
return NULL;
}
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values and list (thanks #nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));

How to parse key/value chain into associative array in PHP?

I have a string that looks like: key1/value1/key2/value2/ and so on
I did an explode('/',trim($mystring,'/')) on that
Now I want to haven an associative array like:
array(
'key1' => 'value1',
'key2' => 'value2',
...
);
of course i can do it with an for loop where i always read two entries and push them into a target array, but isnt there something more efficient and elegant? a one liner with some some php core function similar to ·list()· or something?
A method using array_walk() with a callback function:
function buildNewArray($value, $key, &$newArray) {
(($key % 2) == 0) ? $newArray[$value] = '' : $newArray[end(array_keys($newArray))] = $value;
}
$myString = 'key1/value1/key2/value2/';
$myArray = explode('/',trim($myString,'/'));
$newArray = array();
array_walk($myArray, 'buildNewArray', &$newArray);
var_dump($newArray);
If the format is not changin (i mean it is allways Key1/value1/key2/value2) it should be easy.
After the explode you have this:
$arr = Array('key1','value1','key2','value2')
so you now can do:
$new_arr = array();
$i = 0;
for($i=0;$i<count($arr);$i+=2)
{
$new_arr[$arr[i]] = $arr[$i+1];
}
at the end of the loop you will have:
$new_arr = array("key1"=>"value1","key2"=>"value2")
KISS :)
HTH!
One can always make yourself a one liner.
This is called User-defined functions
No need to devise something ugly-but-one-liner-at-any-cost.
Make your own function and you will get much shorter, cleaner and way more reliable result.
A function, which will not only do elementary string operations but also do something more intelligent, like parameter validation.

Categories