Is there more easiest way and less code to print all the strings inside an array if the index is less than to the number I want and also? example is:
$string = Array(
[0] => A,
[1] => B,
[2] => C,
[3] => D
);
I want to print all string with index less than 3 and also separated by / like this:
A/B/C
I know I can use implode then use foreach with if but I want to know if it can be done with just one line? thanks
You can use array_filter to filter all array keys lower than 3 (or another value):
<?php
$arr = ['A', 'B', 'C', 'D'];
$newArr = array_filter($arr, function($val) {
return $val < 3;
}, ARRAY_FILTER_USE_KEY);
var_dump(implode('/', $newArr)); //string(5) "A/B/C"
demo: https://ideone.com/B1rn6I
I don't recommend to use array_slice. Why? Your title describes your problem and what to do with the array: "print all array string if index is less than something".
So you need a code that removes all elements of the array whose keys are greater than or equal to a certain value (in your case 3). So you can use a for or foreach loop to check each item against this condition and removing the not valid items. Another possibility is to use a solution using array_filter (like the above one).
Why not array_slice: This function only extract a slice from the array independently of the key. You define how this slice should look like but at the end you can't be sure all keys are valid, because you (and array_slice) don't check it.
an example where array_slice don't do what you want:
<?php
$input = ['A', 'B', 'C', 'D', 'E'];
unset($input[1]);
//using array_slice
var_dump(implode('/', array_slice($input, 0, 3))); //string(5) "A/C/D"
//using array_filter
$output = array_filter($input, function($val) {
return $val < 3;
}, ARRAY_FILTER_USE_KEY);
var_dump(implode('/', $output)); //string(3) "A/C"
demo: https://ideone.com/npySEs
If you can be sure the array is complete and no keys are missing you can use array_slice but it is not made to remove specific keys.
You can use sort to sort the values of the array but your keys will be changed:
This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With