简体   繁体   中英

PHP get a specific value from a foreach key

I am trying to extract a value from a foreach loop:

$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);

foreach($telephoneNums as $telephoneNum){
    $telephoneNum = 't'.$telephoneNum;
}

echo $telephoneNum[0];

the value that is being output is t

If I do echo $telephoneNum[1]; I get 4

I'd like to get t1231315 for echo $telephoneNum[0]

This is simple problem but I am not sure what I am doing wrong.

The problem is you're just assigning a string and not pushing an array to assign:

$telephoneNum = 't'.$telephoneNum;

Use the array assignment:

$telephoneNum = array();
foreach($telephoneNums as $tel){
    $telephoneNum[] = 't'.$tel;
               // ^ this is important
}
echo $telephoneNum[0];

Sidenote:

In case you're wondering how echo $telephoneNum[0]; is t and echo $telephoneNum[1]; 4. Is because since the last iteration is the value t42342342 overwriting $telephoneNum (the string) . And this is a behaviour of string access in PHP.

http://php.net/manual/en/language.types.string.php

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.

Try this..

<?php
$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);
$telephoneNum=array();
foreach($telephoneNums as $tele){
   $telephoneNum[] = 't'.$tele;
}
echo $telephoneNum[0];//t1231315
echo $telephoneNum[1];//t42342342
?>

This is how you will need to do. There you are extracting the first character from a string which otherwise you should have extracted from an array:

$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);
$i = 0;
foreach($telephoneNums as $telephoneNum){
  $telephoneNums[$i] = 't'.$telephoneNum;
   $i++;
}

echo $telephoneNums[0]."\n";
echo $telephoneNums[1];

use this code

$telephone1 = '1231315';
$telephone2 = '42342342';

$telephoneNums = array($telephone1,$telephone2);
 $telephoneNumbers=array();
foreach($telephoneNums as $telephoneNum){
    $telephoneNumbers[] = 't'.$telephoneNum;//telephoneNumbers[] is an array
}

echo $telephoneNumbers[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM