0

Just so you know I'm working in WordPress. I have an array and want to create an object with only certain values from that array.

Then I have another separate array, I'd like to add to this new object. I might be over complicating things. If I am, please let me know.

Here's what I have so far:

$custom = get_post_custom(); //Gets array of values
$picObject = (object)$custom; //Creates object
$picCount = $custom['picturecount'][0];
for ($x = 1; $x <= $picCount; $x++) {
     // This assembles a URL that I want to add to the array. 
     $finalUrl = $picUrl.$gsi.'&picfilename='.$vin.'_00'.$x.'.jpg';
}

Let me know if you need anything else. Thanks in advance everyone!

3
  • array_push($arr, $val). Documentation: php.net/manual/en/function.array-push.php Commented Apr 20, 2017 at 19:46
  • 2
    You should show us what $custom looks like and what you expect your final output to be Commented Apr 20, 2017 at 19:47
  • Could you just work with arrays? It's not wrong to want to use an object, but is it necessary? Commented Apr 20, 2017 at 20:21

1 Answer 1

1

If you want to create an object with only some values from your array, you shouldn't cast the array because you'll end up with all of its values. Instead, create a new object and set the values you want:

$array = array(
    'foo' => 'bar',
    'bar' => 'baz'
);

$object = new stdClass();

$object->bar = $array['bar'];
$object->something_else = 'w00t!';

Casting an array to object (i.e. (object)$array) will get you the same type of object, so you can still use $object->new_property = 'foo'; to add stuff to it.

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

3 Comments

this is a pretty primitive way to handle this tho. I mean, it's barely an answer besides how to imperatively construct a new empty object.
Isn't that what he's asking though? To me, his question can be summarised as "how do I create an object from an array, and how do I add something to it?"
Exactly @rickdenhaan.

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.