0

The var_dump of the associative array $myArray is as follows:

array (size=522)
  0 => 
    array (size=3)
      'id' => int 1
      'url' => string 'introduction' (length=12)
      'title' => string 'Introduction' (length=12)
  1 => 
    array (size=3)
      'id' => int 2
      'url' => string 'first_steps' (length=11)
      'title' => string 'First steps' (length=11)
  2 => ...

When I assign the values of elements in the associative array to a function, to perform some string manipulation, I get an error:

"Catchable fatal error: Argument 1 passed to doStringManipulation() must be an instance of string, string given, ..."

The string manipulation is called inside a foreach loop:

foreach($myArray as $row){
    ...
    $s = doStringManipulation((string) $row['url']); // triggers error
    ...
}

function doStringManipulation(string str){
    ...
    return $result; // string
}

Whether or not I cast $row['url'] to string doesn't make a difference. I always get the error, even though var_dump confirms that the element value is a string.

What am I missing here?

Thanks!

5
  • Which php version are you using? Commented Jan 11, 2017 at 12:46
  • Have you tried not placing $row['url'] as a parameter but for example "test" ? (try without the cast) Commented Jan 11, 2017 at 12:47
  • Maybe this can help stackoverflow.com/questions/4103480/… Commented Jan 11, 2017 at 12:54
  • @Robert: using 5.5 Commented Jan 11, 2017 at 13:24
  • @Lazar Petrovic: thanks, indeed, that helps. Commented Jan 11, 2017 at 13:24

2 Answers 2

1

I'm going to assume you're not using php 7.

The error states that it requires an instance of string (which php does not have), this is because you are type hinting string in function doStringManipulation(string str){. Type hinting does not work on anything but on arrays and objects.

My suggestion:

function doStringManipulation($str) { // assuming 'str' was a typo here
    if ( ! is_string($str)) {
         return '';
    }

    ...

    return $result; // string
}

For more info see: http://php.net/manual/en/migration70.new-features.php

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is the most complete answer.
0

You use php version 5.0-5.6. you cant specify string as function argument. Code must looks like

/**
* @var String str
*/ 
function doStringManipulation(str){
    ...
    return $result; // string
}

Or update php up to 7

1 Comment

Thanks. Maybe I was getting code hints that applied to php 7 for some reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.