-1

Please consider this line of code:

$arr = array_filter(explode('/', $path), 'strlen');

and suppose $path variable is a url like:

$path = "http://localhost/oldcodes/test_codes/";

I expect the output of first code would be something like:

array(4) { [0]=> "5"  [2]=> "9"  [3]=> "8" [4]=> "10" }

because strlen function returns length of each string, BUT I get this result:

array(4) { [0]=> string(5) "http:" [2]=> string(9) "localhost" [3]=> string(8) "oldcodes" [4]=> string(10) "test_codes" }

could you please give me any hint why the result is in this way! Thanks

0

2 Answers 2

2

Basically "your problem" is because explode breaks down a string using a delimiter from a string in your case you are using / this means in your case you have the following string:

http://localhost/oldcodes/test_codes/

Breaking the string using the / separator would return.

  • http
  • ''
  • 'localhost'
  • 'oldcodes'
  • 'test_codes'
  • ''

When the output of this function is passed down to array_filter this function would return any value that is evaluated to true using loose comparisision in this case empty strings are considered false and not empty strings are evaluated to true that's why empty strings are removed from your output. Reference

You can always pass a callback (another function) as second parameter to array_filter to filter specif elements instead, or to define a custom logic to filter elements out of an array.

And if you are looking to get the length of each of those components you need to swap array_filter with array_map instead.

$arr = array_map( 'strlen', array_filter( explode('/', $path) ) );
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your great explanation. my question is when an element passed to array_filter by strlen as a callback function, if the element length is greater than zero then why strlen function does not return the length of the element??! as this is the default behavior of this function!
Great question, array_filter does not return the output of the function you use (in your case strlen) array_filter only uses the function you passed to evaluate the current value in the array if the value evaluates to true (in your case any length != 0 would be true) and all of those elemenets that evaluates to true are returned as they are no change is applied to the original values that's why you need to use array_map which does exactly that maps over an array and returns the output of the function you passed for each element instead.
2

Just you need to use array_map instead array_filter:

<?php
$path = "http://localhost/oldcodes/test_codes/";

$arr = array_map(
    'strlen',
    explode('/', $path)
);

var_dump($arr);

Here the code

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.