-1

I keep getting the following error in PHP:

[13-Jul-2019 06:49:43 UTC] PHP Warning: Illegal string offset 'text' in /home/catchandreport/public_html/sweettune.info/LikeDislike/index.php on line 15

Is there any way that I can replace my string with something else?

I haven't tried anything yet. While I'm at it, this is a totally different problem, but in another line of code I get

Illegal string offset 'id'

Is there something I'm doing wrong that I can change?

  <?php echo $post['text']; ?>
  <div class="post-info">
    <!-- if user likes post, style button differently -->
    <i <?php if (userLiked($post['id'])): ?>
          class="fa fa-thumbs-up like-btn"
      <?php else: ?>
          class="fa fa-thumbs-o-up like-btn"
      <?php endif ?>
      data-id="<?php echo $post['id'] ?>"><img src="catlogo.ico"></i>
    <span class="likes"><?php echo getLikes($post['id']); ?></span>
Watercayman
  • 7,970
  • 10
  • 31
  • 49
Deskie
  • 45
  • 4

3 Answers3

0

It sounds like the value $post["text"] isnt set in your array.

If you are not sure that the array section/key you are using exist, you should always test for it first:

$textVar = (isset($post["text"]) ? $post["text"] : "YOUR ALTERNATE VALUE");

Maybe even check if your array is set:

$post = (is_array($post) ? $post : array());

If you cant get the correct value, then try to var_dump your array to see the type and content:

var_dump($post);

Hope it helps

SeeQue
  • 51
  • 6
  • as @JureW metioned, using "array_key_exists" might be a better idea since "isset" will return FALSE if your array value is NULL. Please let us know if this solved your problem – SeeQue Jul 17 '19 at 19:19
0

Illegal string offset warning will come when the variable type is not array and you're trying to access the array key value.

Let me give you an example (Wrong Way);

$post = ''; // Initialized as empty string
$post['text'] = 'abc'; // It will work but give you illegal offset value

echo $post['text']; // It will work but give you illegal offset value

Example of doing in correct way:

$post = array(); // Initialied as array
$post['text'] = 'abc';  // Now it will not give the illegal offset value

echo $post['text']; // Now it will not give illegal offset value
Ashok Gadri
  • 520
  • 4
  • 11
0

If you have a problem with illegal string offset, first, as @SeeQue already mentioned,

Test if post is an array, than test for keys, not if they are set, but if they are there:

                if(is_array($post)) {
                   if(array_key_exists("text", $post)) {
                    //do something
                  }
                }

Maybe this could help.

BR

JureW
  • 641
  • 1
  • 6
  • 15