title: Verifying if entry exists in json array with php before posting to server
body: <p>I'm trying to figure out the best way to find a combination of values in a json array and if it exists, return an error message. If the combination of values is not present in the array, post them to the server. Here is what I have so far.</p>
  
  <p>JSON</p>
  
  <pre><code>[{
    "username": "johnsmith@test.com",
    "contest": "TV",
    "timestamp": "Fri Nov 09 2018 16:33:38 GMT-0500 (Eastern Standard Time)"
  }, {
    "username": "bob@test2.com",
    "contest": "Phone",
    "timestamp": "Fri Nov 09 2018 18:33:51 GMT-0500 (Eastern Standard Time)"
  }]
  </code></pre>
  
  <p>I'm using ajax to post the details to php and that part works well.</p>
  
  <pre><code>        $.ajax({
              type: 'POST',
              url: 'update.php',
              data: { theuser: theuser, thecontest: thecontest, timestamp: timestamp },
              success: function() {
                  //Show confirm notification hide btns and close the modal
                  $('.modalbtns').hide();
                  $('#successbox').fadeIn();
                  setTimeout(function() {
                      $('#ModalCenter').modal('hide')
                  }, 2400);
              },
              error: function() {
                  // do something on error
              }
          });
  </code></pre>
  
  <p>This is what I have so far for the php (update.php)</p>
  
  <pre><code>&lt;?php
  
  $theuser = $_POST['theuser'];
  $thecontest = $_POST['thecontest'];
  $timestamp = $_POST['timestamp'];
  
  if (is_writable('alldata.json')) {
  
      $json = file_get_contents('alldata.json');
      $data = json_decode($json);
      $data[] = array('username'=&gt; $theuser, 'contest' =&gt; $thecontest, 'timestamp' =&gt; $timestamp);
      file_put_contents('alldata.json', json_encode($data));
  
  } else {
      //echo "file is not writable, check permissions";
  }
  
  ?&gt;
  </code></pre>
  
  <p>For example what I'm trying to achieve is</p>
  
  <p>Before posting, check in the json array if the following combination exists.
  <strong>username = bob@test2.com AND contest = Phone</strong>
  If it exists, return a custom message to the page e.g. (you already registered).
  If the combination is not in the json array, post to the file.</p>
  
  <p>I believe it has to be something in the lines of </p>
  
  <pre><code>foreach($data as $item)
  {
      if($item-&gt;username == $username) || ($item-&gt;contest == $contest){
          //combination found, do not post!
      }
  }
  </code></pre>
  
  <p>But I can't get it to work, thanks for the help!</p>