checkopenport
checkopenport

Reputation: 121

PHP cannot use a scalar as an array warning issue

I have an problem on my website i've made an hits counter :

$count = ("hits.txt"); 
$clicks = file($count);
if ($clicks > 5){$clicks = 0;}
$clicks[0]++;
$fp = fopen($count , "w");
fputs($fp , "$clicks[0]");
fclose($fp);

but i receive this message : cannot use a scalar as an array warning issue

Upvotes: 0

Views: 71

Answers (1)

h2ooooooo
h2ooooooo

Reputation: 39532

Woah - I don't know what's going on in your code here.

  • Why is your string in parenthesises? It works, it's just odd
  • Why do you use brackets on a single-condition-line? You can skip the brackets
  • Why do you have your array in quotes, when it's a variable? If it's a variable, don't quote it
  • Why do you use file to read the file instead of a simple file reader? Use fopen, file_get_contents or other solutions to simply read a number off a text file

Your example could very easily be rewritten to the following:

<?php
    $count = (int)file_get_contents("hits.txt");
    file_put_contents("hits.txt", ($count > 10 ? 1 : $count + 1));
?>

Upvotes: 1

Related Questions