Search code examples
phparraysloopskeyassociative-array

Populate associative array using dynamic keys in a loop


How do I replace the array key of the 2nd array with the value of my 1st Array?

$imgNumbers = array();
foreach($imgPat as $imgKey => $imgValue)
{
    $imgNumbers[] = intval(substr($imgValue, strrpos($imgValue, '/') +4));
}


$images = array();
foreach($imgPat as $imgKey => $imgValue) {
    $images[] = img_to_base64($imgValue);
}

$imgNumbers Returns integers like 2,24 or 111.

and $images shall have as an Array key $imgNumbers.


Solution

  • You could do it in a single loop:

    $images = array();
    foreach($imgPat as $imgKey => $imgValue)
    {
        $imgNumbers = intval(substr($imgValue, strrpos($imgValue, '/') +4));
        $images[$imgNumbers] = img_to_base64($imgValue);
    }