Can I collect explode then explode again? - php

I'm trying to create data save variable using a text file. I read that the collect function in laravel is the right choice for managing the data.
Here is the data saved after I exploded with PHP_EOL :
What I want to do is explode once more per array with "|", so my code is like this but it can't.
$temps=explode(PHP_EOL,$note);
$isi=collect([
explode('|',$temps)
]);
This code can only be applied if it is accompanied by a manual array like this :
$isi=collect([
explode('|',$temps[0]),
explode('|',$temps[2])
]);
The dd output:

As I think you've worked out, explode returns an array but accepts a string, so you can't pass the result of explode directly to another explode call.
Instead you need to get each individual string in the array produced by the first explode, and explode each one separately.
Clearly it's not practical to try and hard-code a reference to each item of the array (as per your attempt), so instead you can use a loop to fetch each item, or a slightly neater way is to use array_map, like in the following example:
function pipeExplode($str)
{
return explode("|", $str);
}
$text = "sdlkfjsdl|kwflwerflwekr|wlkjlgk4w\n3rtljhrfgkjed|3jhkrjghd|4t44thj\n33rtlhwege|3rth3herjgke|hkjfgdf";
$arr = explode(PHP_EOL, $text);
$finalArr = array_map('pipeExplode', $arr);
print_r($finalArr);
Demo: https://3v4l.org/EM6Ct
This will take each string from the first array, pass it through the pipeExplode function to get a new array back from that, and then add that array back into the outer array which is returned by the array_map function.

Related

php function sometimes pushing arrays other times objects

I have an app which i'm making a HTTP request via PHP to retrieve some XML data. I'm then taking a string in that data, splitting it by spaces (" ") and pushing it into a new array. I'm then taking an existing array and de-duping it against this new array using the function array_diff. Here is my code below:
// THIS ARRAY IS MUCH LONGER BUT HAVE JUST PUT IN A FEW WORDS
$stopwords = array("a", "about", "above", "above", "across", "after", "afterwards", "again");
// this is my XML call
$test = simplexml_load_file('https://some-xml-endpoint.com/endpoint');
// defining a blank array where I want the result to go
$mappedWordsObj = [];
for($i = 0;$i < count($test->data);$i++) {
// if I echo this it returns me a string with no quotes (sometimes the quotes would be in there and I thought this may have been the issue)
$comment = chop(strtolower($test->data[$i]->comments));
// here I split the comment into an array by spaces
$wordsArray = explode(' ', $comment);
//here I compare my new array of words with the stopwords I want removed from the wordsArray
$arr_1 = array_diff($wordsArray, $stopwords);
// here I push into the $mappedWordsObj array
array_push($mappedWordsObj, $arr_1);
}
// here I push to the DOM the result to see how my array looks
echo json_encode($mappedWordsObj);
My issue is that in the resulting $mappedWordsObj array, I expect all the array items to be arrays themselves that contain the words but some of the items are getting inserted in the $mappedWordsObj as arrays with the words and others as objects with properties whos values are the words. Here is a snippet of the data returned:
{"0":"i","1":"just","2":"want","4":"switch","6":"existing","7":"t-mobile","8":"pay","13":"ee","14":"pay","15":"monthly.","16":"i","17":"don't","18":"want","20":"new","21":"phone!","23":"page","24":"does","26":"tell","31":"this!"},{"0":"just","2":"option","4":"'sim","5":"only'","9":"'radio","10":"button'","11":"forced","12":"selection."},
["voice","recignition"],
["testing","ol"],
{"0":"can't","1":"think","4":"i","7":"simple","9":"easy"},{"2":"instead","3":"lol"},
["n\/a"],
["great","website"],
I'd like to just have an array of arrays so can anyone please tell me where i've gone wrong?
Cheers
When you use json_encode, it will convert PHP arrays to either JSON arrays or JSON objects. Which one is output depends completely on the array keys in the PHP array. For PHP arrays with sequential, numeric indexes starting at 0, the JSON output will be an array. For PHP arrays with any other indexes, the JSON output will be an object.
The array_diff produces an array where the indexes are not sequential in some cases. You can use array_values to reindex the result before appending it to your output array.
array_push($mappedWordsObj, array_values($arr_1));
Side note - array_push actually isn't necessary here. You can use
$mappedWordsObj[] = array_values($arr_1);
The array_push documentation actually recommends doing it this way when you're only appending one item to the array. But, it's a pretty small optimization, so if array_push looks better to you, never mind. :)

php array_search not returning values

I am putting the contents of an text file into an array via the file() command. When I try and search the array for a specific value it does not seem to return any value but when I look at the contents of the array the value I am searching for is there.
Code used for putting text into array:
$usernameFileHandle = fopen("passStuff/usernames.txt", "r+");
$usernameFileContent = file("passStuff/usernames.txt");
fclose($usernameFileHandle);
Code for searching the array
$inFileUsernameKey = array_search($username, $usernameFileContent);
Usernames.txt contains
Noah
Bob
Admin
And so does the $usernameFileContent Array. Why is array_search not working and is there a better way to do this. Please excuse my PHP noob-ness, thanks in advance.
Because file():
Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached
To prove this try the following:
var_dump(array_search('Bob
', $usernameFileContent));
You could use array_map() and trim() to correct the behavior of file(). Or, alternatively, use file_get_contents() and explode().
To quote the docs:
Each element of the array corresponds to a line in the file, with the newline still attached.
That means that when you're doing the search, you're searching for "Noah" in an array that contains "Noah\n" - which doesn't match.
To fix this, you should run trim() on each element of your array before you do the search.
You can do that using array_map() like this:
$usernameFileContent = array_map($usernameFileContent, 'trim');
Note, too, that the file() function operates directly on the provided filename, and does not need a file handle. That means you to do not need to use fopen() or fclose() - You can remove those two lines entirely.
So your final code could look like this:
$usernameFileContent = array_map(file('passStuff/usernames.txt'), 'trim');
$inFileUsernameKey = array_search($username, $usernameFileContent);

Elegant way to force two array elements when splitting a string

Assume the following string:
$string = 'entry1_entry2';
What I want to do is something like this:
list($entry1, $entry2) = explode('_', $string);
My question now is are there any elegant ways to force the explode (or any other function) to get 2 array items minimum? You could specify a third parameter to get a maximum of 2 elements but I want a minimum. If there would be a string like this:
$string = 'entry1';
The second line would give a NOTICE because there is only one array element. The best would be a way without checking the resulting array or the string for the presence of the seperator.
You could probably use array_pad:
list($entry1, $entry2) = array_pad(explode('_', $string), 2, NULL);
See array_pad
I'd suggest that storing the explode inside multiple variables is just bad practice, when you can't enforce the integrity of your data.
Should you not simply be using
$entries = explode($string);
and avoid all the unnecessary complications?

Can't flatten multidimensional array with lots of duplicates

I'm trying to create a script that, based on an input a?? creates an array of all the combinations and permutations of all words containing an a and two other characters from the alphabet.
Values are such as a, ab, ba, dab, bga etc - as you may see the array contains (or should contain) a weird amount of values.
The problem is that the functions I use in the script outputs even more values with many duplicates.
And for some reason I can not create a flattened array without duplicates. I tried to use array_unique() but it doesn't work here. I tried to use explode() and implode() to flatten the result array, but no success. Even if I succeed to create a string from the values, when I try to transform this string into an array, the result is again the actual multi-dimensional array.
This drives me crazy, and as you see the code, I'm a beginner in PHP.
Any help to transform the actual multidimensional array to a flattened one without duplicates is highly appreciated. An example: actually the array contains 12168 sub-arrays, and only the string a occurs 1456 times. What I need is an array that doesn't have sub-arrays and contains each results only one time.
The PHP code is available at here
and the output is here:
Have you tried something like:
$inputString = 'a??';
$array = array();
if (strpos($inputString, 'a') !== false && !in_array($inputString, $array)) {
$array[] = $inputString;
}
echo '<pre>'; print_r($array); echo '</pre>';

Get arbitrary number of random elements from a php array in one line

I wanted to pull an arbitrary number of random elements from an array in php. I see that the array_rand() function pulls an arbitrary number of random keys from an array. All the examples I found online showed then using a key reference to get the actual values from the array, e.g.
$random_elements = array();
$random_keys = array_rand($source_array);
foreach ( $random_keys as $random_key ) {
$random_elements[] = $source_array[$random_key];
}
That seemed cumbersome to me; I was thinking I could do it more concisely. I would need either a function that plain-out returned random elements, instead of keys, or one that could convert keys to elements, so I could do something like this:
$random_elements = keys_to_elements(array_rand($source_array, $number, $source_array));
But I didn't find any such function(s) in the manual nor in googling. Am I overlooking the obvious?
What about usung array_flip? Just came to my mind:
$random_elements = array_rand(array_flip($source_array), 3);
First we flip the array making its values become keys, and then use array_rand.
An alternate solution would be to shuffle the array and return a slice from the start of it.
Or, if you don't want to alter the array, you could do:
array_intersect_key($source_array, array_combine(
array_rand($source_array, $number), range(1, $number)));
This is a bit hacky because array_intersect can work on keys or values, but not selecting keys from one array that match values in another. So, I need to use array_combine to turn those values into keys of another array.
You could do something like this, not tested!!!
array_walk(array_rand($array, 2), create_function('&$value,$key',
'$value = '.$array[$value].';'));

Categories