0

I'm sure this is trivial to an expert, I just don't know how to do it exactly.

I have a for loop

for ($x = 1; $x <= $picCount; $x++) {
    $finalUrl = $picUrl.$gsi.'&picfilename='.$vin.'_'.sprintf('%03d', $x) .'.jpg';
}

What I want to do is add each $finalUrl to the object or an array. How do I do that?

Example of final object:

stdClass Object
(
  [title] => Blah
  [test] => w00t!
  [picUrl] => array(
        http://example.com/image/xx1.jpg
        http://example.com/image/xx2.jpg
        http://example.com/image/xx3.jpg
        http://example.com/image/xx4.jpg
     )
)
5
  • 1
    Please provide an example of the result you want to get. Commented Apr 21, 2017 at 18:36
  • Added an example. Please excuse the bad formatting.... Commented Apr 21, 2017 at 18:44
  • So you are basically asking how to add a value to an array? Have you read any documentation or at least searched Stack Overflow? Commented Apr 21, 2017 at 18:51
  • @FelixKling. I did, but I am looking to add an array from a for loop. I couldn't find what I was looking for Commented Apr 21, 2017 at 18:56
  • 1
    It doesn't matter from where an element is added from. The loop is irrelevant. If $foo is an array, then $foo[] = $bar; or array_push($foo, $bar) will append an element to that array. Commented Apr 21, 2017 at 18:58

3 Answers 3

1

Simply set $finalUrl as an array:

$finalUrl = [];
for ($x = 1; $x <= $picCount; $x++) {
    $finalUrl[] = $picUrl.$gsi.'&picfilename='.$vin.'_'.sprintf('%03d', $x) .'.jpg';
}
Sign up to request clarification or add additional context in comments.

Comments

0

So, assuming in the end you want an array of strings, this can be easily accomplished doing:

$a = [];
for ($x = 1; $x <= $picCount; $x++) {
    $finalUrl = $picUrl.$gsi.'&picfilename='.$vin.'_'.sprintf('%03d', $x) .'.jpg';
    $array[] = $finalUrl
}

return $a;

This will return an array of every $finalUrl values.

Breakdown:

$a = [] Initializes an array.

$a[] = $finalUrl Pushes $finalUrl to the array

Comments

0
$newArray = array();     // Will contain a list of $finalUrl
for ($x = 1; $x <= $picCount; $x++) {
    $finalUrl = $picUrl.$gsi.'&picfilename='.$vin.'_'.sprintf('%03d', $x) .'.jpg';
    $newArray[] = $finalUrl;
}

$newArray is the array of $finalUrl's created in the prior loop. print_r($newArray) will display it's contents.

Comments

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.