Get index of value from array in php

I have the following php array $tempStyleArraythat is created by using a string.

$tempStyleArray = preg_split( "/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;" );


Array
(
    [0] => width
    [1] =>  569px
    [2] =>  height
    [3] =>  26.456692913px
    [4] =>  margin
    [5] =>  0px
    [6] =>  border
    [7] =>  2px solid black
    [8] => 
)

I need to get an index/keyelement heightfrom this array. I tried under the codes, but nothing works for me.

foreach($tempStyleArray as  $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     $key = $i;
   }
} 

in the above solution, it does not satisfy the condition: (

$key = array_search('height', $tempStyleArray); // this one not returning anything

Help me solve this? Is there a problem with my array?

+4
source share
5 answers

Try it -

$tempStyleArray = array_map('trim', preg_split( "/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;" ));
var_dump($tempStyleArray);
$key = array_search('height', $tempStyleArray);
echo $key;

This happened because it was spacewith values ​​in array. So you need to be trimmed. After splitting the string, each value will be passed through trim()to delete white spaces.

+2
source
foreach($tempStyleArray as  $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     $key = $i;
   }
} 

$i?, key = > .

foreach($tempStyleArray as  $key => $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     echo $key;
   }
} 

, , , "" 569 , , , :

$tempStyleArray = array(
    "width" =>  "569px",
    "height" => "26.456692913px",
    "margin" => "0px",
    "border" => "2px solid black"
);

echo $tempStyleArray["width"];

, .

UPDATE:

for( $i == 1; $i < count($tempStyleArray); $i = $i+2)
{
    $newArray[ $tempStyleArray[$i-1] ] = $tempStyleArray[$i]
}

, -.

+4

You are accepting invalid values ​​from an array

It should be

 foreach($tempStyleArray as $temp => $value) {
    if($value == "height") // will satisfy this condition
    { 
        echo $value; 
        echo '</br>'; 
        $key = $i;
    }
 } 
+2
source

Use as follows (treat like an array associative)

foreach($tempStyleArray as   $key => $value){
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     echo $key;
   }
}
+2
source

There are errors in your code. Try:

foreach($tempStyleArray as  $key => $value)
{
   if($value == "height") 
   {
     echo $key;
   }
} 
+1
source

Source: https://habr.com/ru/post/1583929/


All Articles