The differential treatment of arrays' values in comparison to manually inputted values

Here is a function that I have:

public function getReward($formattedArray, $key){
    $id = $formattedArray[$key][0];
    //dd($id); //Returns 1
    $reward = Item::find($id); 
    return $reward;
}

The problem arises when executing this part of the code:

$reward = Item::find($id); 

After debugging and using dd() to check the value of the variable 'id', it returns the expected value of 1. However, when this value is used in the static find function at the end, an error occurs stating "Trying to get property of non-object".

To resolve this, I made a change:

$reward = Item::find($id); //Changed to...
$reward = Item::find(1);

The only difference here is that I manually input the integer 1 into the static find function. With this modification, the code now works flawlessly without any errors and I am able to access the object returned.

Working Example:

$reward = Item::find(1); 
return $reward;

Working Example:

$reward = Item::find("1"); 
return $reward;

Non-working Example:

$reward = Item::find($formattedArray[$key][0]); 
return $reward;

I also attempted casting the 'id' variable to an integer like this:

$id = $formattedArray[$key][0];
$idInt = (int) $id;
$reward = Item::find($idInt);
return $reward;

Answer №1

I believe the $id you are receiving is not of object type. To verify this, you can use var_dump(). It seems that your Item::find() function is attempting to access a field that is not accessible.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js - Resetting child components upon array re-indexing

I am working with an array of objects const array = [ { id: uniqueId, childs: [ { id: uniqueId } ] }, { id: uniqueId, childs: [ { id: uniqueId } ] }, ] and I have a looping structure ...

Deciding between a pair of Meta Tags options

My current project involves extracting meta tags from websites and displaying the results. The code I am using has been working well, but I have encountered an issue... This is the code snippet in question: static private function _parse($HTML) { $ol ...

When using PHP in Wordpress, the previous post link may unexpectedly display on the final post in the

Essentially, the following code displays the next category of posts instead of omitting it. <div class="post-previous"><?php previous_post_link('%link', true); ?></div> I would expect this to be hidden if it's in the last ...

Troubleshooting Problem with Prepared Statements in PHP/MySQL

Currently, I am working on a PHP/MySQL project and have encountered an issue that I need help with. The project involves creating a platform where users can input their financial accounts (such as bank accounts and credit cards) along with monthly transact ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

Ensure the proper ordering of indexes in PHP arrays

Currently, I am exploring the most effective method to perform a specific test in PHP. The task involves analyzing a list of numbers and identifying any missing indices in the succession of these numbers. If there are missing indices, an alert needs to be ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Minify causes AngularJs to error out

When I minify my AngularJS code, I encounter an error: The module 'app' failed to instantiate due to: Error: [$injector:unpr] Unknown provider: t The code only works when using gulp without the --production flag. //All dependencies used below ...

What is the best way to incorporate the req parameters into the SQL query?

The Situation In the process of developing a node app, I encountered an issue with injecting the result of multiple SQL queries into an EJS view. Initially, I had successfully implemented a single query within the app.get() function. This query retrieved ...

Using HTML as an argument in a JavaScript function

Within a variable, I have stored an entire HTML page. $body = $myhtmlpage; <a onclick="openWin('<?php echo htmlspecialchars(json_encode($body)) ?>');" href="javascript:void(0);"> Click </a> I also have this JavaScript functio ...

Using Ajax to compare the user input with a value stored in an object and then determine the corresponding id of that object

From my API, I receive an array that looks like this: Array [Object, Object, Object, Object, Object] // if stringified [{"id":"0","name":"user1","type":"mf","message":"bonjour user1"}, {"id":"1","name":"user2","type":"ff","message":"hello user2"}, {"id": ...

Issue with Laravel's with() method and search functionality using LIKE is not functioning as expected

My current setup involves 2 tables. One table is for storing debt information (id, amount, category_id), while the other table is used for debt categories (id, name). I am attempting to retrieve data based on each month from the debt table. However, I have ...

Replacing parts of a string with str_replace function

I'm currently exploring the functionalities of str_replace and using curly brackets. When I input {the_title} in this line, I understand that it will be replaced with the value from the $some_runtime_generated_title array. But what exactly does the fi ...

Unfortunately, I am currently unable to showcase the specifics of the items on my website

I am trying to create a functionality where clicking on a product enlarges the image and shows the details of the product as well. While I have successfully implemented the image enlargement, I am facing challenges in displaying the product details. Below ...

PHP is featured in the Lazy Classes program

Currently, I am using an autoloader to include classes by using "glob" to read different directories and push them into an array. Is there a more efficient method for accomplishing this task? $path = './'; $files = array_merge( glob($path.&apos ...

Instructions on creating a PHP file key that automatically expires after 10 days, preventing other users from accessing the API once the key has expired

My goal is to create a key that remains valid for 10 days from the date of generation. This key should allow anyone to access an API for a period of 10 days. I specifically want to implement this functionality using PHP only, without relying on sessions or ...

Exploring the intricacies of the Zend Framework Bootstrap procedure and how resources are loaded from the application

Although I consider myself quite knowledgeable about Zend Framework and how it operates, there is one aspect that still eludes me: the process by which Zend Framework accesses resources from application.ini. I am aware that I can create my own protected _ ...

Get rid of the .php extension in the URL completely

Lately, I've been experimenting a lot with the .php extension. I successfully used mod_rewrite (via .htaccess) to redirect from www.example.com/example.php to www.exmaple.com/example. Everything is running smoothly. However, I noticed that even though ...

Dealing with form submission issues in jQuery and jqGrids

Lately, I've been experimenting a lot with jqgrids and have almost everything set up the way I want it - from display to tabs with different grids. Now, I'm trying to utilize Modals for adding and editing elements on my grid. The issue I'm ...

What steps can I take to create efficient live forms using AJAX and jQuery only?

I've been attempting to create AJAX forms but have had no success so far. I experimented with iframes, but found them to be not as effective. However, these are the only methods I have tried and am familiar with. Although I attempted to use the $.AJA ...