0

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.

3 Answers 3

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Write the value of $imgNumbers with index as key when second array created

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


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

Comments

0

Better to merge them in one loop for better performance, something like this:

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

The previous are more readable but you can decrease the process by merge them and ignore the $imgNumbers brigde like this:

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

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.